by BehindJava

How to create Rest Controller class in Spring Boot

Home » springboot » How to create Rest Controller class in Spring Boot

In this tutorial we are going to learn about creating a Rest Controller class in Spring application in detail.

Once we create our Spring application using Spring Initializr, doesn’t work as a Restful web service and even if we run this it cannot receive or send any HTTP request or response.

Firstly, we will start creating a new package in the folder structure and under the controller package we will create a new class as a user controller.


When we start the Spring Boot application the controller class specified should be able to receive the HTTP requests we need to add a couple of annotations which very important i.e. @RestController and @RequestMapping to map URL’s to the instance methods of the class.

@RestController : This is a class level annotation which registers the class a rest controller to receive the HTTP requests.
This annotation is a combination @Controller and @ResponseBody.
@Controller : It is class level annotation and a meta annotation of component. So beans annotated with this annotation are automatically imported into spring container.
@ResponseBody : This annotation tells the controller that object returned is automatically serialized into JSON and passed back to the HTTP response object.

Sample code snippet:

package com.behindjava.tutorial.controller;

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

@RequestMapping("users") //http://localhost:8080/users/method 
public class UserController {

And when I send HTTP requests to the one of the methods defined in this user controller will be invoked by the URL i.e. http://localhost:8080 because it is running in Tomcat port number 8080 and now we should provide request mapping so that appropriate method will be triggered from the user controller class i.e. http://localhost:8080/users/method.

Previous                                                                                                               Next