Creating controller class java

Creating your Spring Controller

Using the IntelliJ IDEA New Project Wizard to create your Spring Controller and select dependencies.

Create your Spring Controller

Now we have our functioning Spring project we need to create a Spring Controller to handle the web requests.

Create our Controller

One important thing to note here is that you don’t need to tell your Spring Application class about your (new) Spring Controller class. That is handled by the @SpringBootApplication annotation in the Application class which also consists of other annotations, including @ComponentScan . This means that the current package, and sub packages will be scanned for Spring components. It’s a little unnerving when you first start using Spring but in time you’ll get used to it once you have an appreciation of what Spring is doing behind the scenes for you.

  1. Create a new Java class in the same place as your HelloWorldApplication.java class called HelloWorldController.java .
  2. The first thing we need to do is tell Spring that this is a REST Controller, so you need to add a class level annotation of @RestController . This annotation means this class will be picked up by the component scan, because it’s in the same package as our Application class. Our REST Controller, HelloWorldController , will therefore be available from the application context.
  3. The next step is to create a method that will tell Spring that if we go the root of our webserver, we would like to see the string Hello World from Spring Boot. To do that we need to add a method with a @RequestMapping annotation like our helloWorld one here:
package com.example.helloworld;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController

@RequestMapping("/")
public String helloWorld()
return "Hello World from Spring Boot";
>
>
  1. Now we need to re-run our Spring application. You might need to stop it first if it’s still running from the previous step. You can run it again with Ctrl+R (macOS), or Shift+F10 (Windows/Linux).
  2. When you go to the browser, enter the following URL localhost:8080 . You should see your text being returned:

Hello World being displayed in the browser

  1. Assuming that’s working correctly, you can start to get more adventurous. Try adding this new code below your first method:
@RequestMapping("/goodbye")
public String helloWorld()
return "Goodbye from Spring Boot";
>
  1. Now run your application again. At the root you should still see Hello World from Spring Boot because the @RequestMapping is / indicating root. However, if you now type in localhost:8080/goodbye , you should see Goodbye from Spring Boot.

That’s it! You’re done, congratulations on creating your first Spring Application and serving some text in the browser! In the next section we’ll create a test for our application.

Источник

Quick Guide to Spring Controllers

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Introduction

In this tutorial, we’ll focus on a core concept in Spring MVC, Controllers.

2. Overview

Let’s start by taking a step back and examining the concept of the Front Controller in the typical Spring Model View Controller architecture.

At a very high level, the main responsibilities include:

  • intercepting incoming requests
  • converting the payload of the request to the internal structure of the data
  • sending the data to Model for further processing
  • getting processed data from the Model, and advancing that data to the View for rendering

Here’s a quick diagram for the high level flow in Spring MVC:

SpringMVC

As we can see, the DispatcherServlet plays the role of the Front Controller in the architecture.

The diagram is applicable to both typical MVC controllers, as well as RESTful controllers, with some small differences (described below).

In the traditional approach, MVC applications aren’t service-oriented; therefore, there’s a View Resolver that renders final views based on data received from a Controller.

RESTful applications are designed to be service-oriented and return raw data (JSON/XML, typically). Since these applications don’t do any view rendering, there are no View Resolvers, and the Controller is generally expected to send data directly via the HTTP response.

Let’s start with the MVC0-style controllers.

3. Maven Dependencies

In order to work with Spring MVC in Spring Boot, we’ll deal with the Maven dependencies first:

 org.springframework.boot spring-boot-starter-web 3.0.2 

To get the latest version of the library, have a look at spring-boot-starter-web on Maven Central.

4. Spring Boot Web Config

Now let’s look at how we can configure the Spring Boot. Since we added the thymeleaf dependency in the classpath, we won’t need to configure any @Beans for that:

 org.springframework.boot spring-boot-starter-thymeleaf 

In our WebConfig, we’ll need to add a bean for the Geeting object and the ObjectMapper in order to enable the default servlet:

 @Bean public WebServerFactoryCustomizer enableDefaultServlet() < return factory ->factory.setRegisterDefaultServlet(true); > @Bean public Greeting greeting() < Greeting greeting = new Greeting(); greeting.setMessage("Hello World !!"); return greeting; >@Bean public ObjectMapper objectMapper()

So, for example, if the Controller returns a view named “welcome”, the view resolver will try to resolve a page called “welcome.html” in the templates folder. This is the default folder where thyeamleaf will search for views.

5. The MVC Controller

Now we’ll finally implement the MVC style controller.

Notice how we’re returning a ModelAndView object that contains a model map and a view object; both will be used by the View Resolver for data rendering:

@Controller @RequestMapping(value = "/test") public class TestController < @GetMapping public ModelAndView getTestData() < ModelAndView mv = new ModelAndView(); mv.setViewName("welcome"); mv.getModel().put("data", "Welcome home man"); return mv; >>

So what exactly did we set up here.

First, we created a controller called TestController and mapped it to the “/test” path. In the class, we created a method that returns a ModelAndView object, and is mapped to a GET request. Thus, any URL call ending with “test” will be routed by the DispatcherServlet to the getTestData method in the TestController.

And, of course, we’re returning the ModelAndView object with some model data for good measure.

The view object has a name set to “welcome“. As discussed above, the View Resolver will search for a page in the templates folder called “welcome.html“.

Below we can see the result of an example GET operation:

6. The REST Controller

The setup for a Spring RESTful application is the same as the one for the MVC application, with the only difference being that there are no View Resolvers or model map.

The API will generally return raw data back to the client, XML and JSON representations usually, so the DispatcherServlet bypasses the view resolvers and returns the data right in the HTTP response body.

Let’s have a look at a simple RESTful controller implementation:

@RestController public class RestController < @GetMapping(value = "/student/") public Student getTestData(@PathVariable Integer studentId) < Student student = new Student(); student.setName("Peter"); student.setId(studentId); return student; >>

We can see a quick snapshot of the output below:

The above output is a result of sending the GET request to the API with the student id of 1.

One quick note here is that the @RequestMapping annotation is one of those central annotations that we’ll really have to explore in order to use to its full potential.

7. Spring Boot and the @RestController Annotation

The @RestController annotation from Spring Boot is basically a quick shortcut that saves us from always having to define @ResponseBody.

Here’s the previous example controller using this new annotation:

@RestController public class RestAnnotatedController < @GetMapping(value = "/annotated/student/") public Student getData(@PathVariable Integer studentId) < Student student = new Student(); student.setName("Peter"); student.setId(studentId); return student; >>

8. Conclusion

In this article, we explored the basics of using controllers in Spring Boot, both from the point of view of a typical MVC application, as well as a RESTful API.

As usual, all the code in the article is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Читайте также:  Add html зеро блок
Оцените статью