Skip to main content
Advertisement

3.1 @RestController and @RequestMapping

When building a web application with Spring Boot, let's learn about the 'Controller', which acts as the gatekeeper receiving the user's initial requests.

1. @Controller vs @RestController

There are two main annotations for declaring a controller in Spring. In modern REST API servers, @RestController is primarily used.

  • @Controller: Mainly used in traditional server-side rendering environments (JSP, Thymeleaf). It finds an ** HTML View file**based on the string returned by the method and sends it as a response.
  • @RestController: The standard for modern REST API environments communicating with frontends (React, Vue) or mobile apps. Instead of finding an HTML screen, it automatically converts the returned data into ** JSON format**and injects it directly into the response body.

(@RestController is internally a combination of @Controller and @ResponseBody.)

2. URL Mapping with @RequestMapping

Once you have set up a gatekeeper (controller), you must map paths so that a specific method is executed when a request comes to a particular URL address.

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

@RestController // Designates as a REST API controller (responses are JSON)
public class HelloController {

// This method is executed when accessing the "/hello" address
@RequestMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!"; // Only pure string data is sent back to the browser
}
}

Class-level @RequestMapping

When designing an API, the front part of the URL often overlaps. In this case, you can specify a Base Path by attaching @RequestMapping to the top of the class.

@RestController
@RequestMapping("/api/v1/users") // All methods in this class will start with this path
public class UserController {

// The actual full URL called: "/api/v1/users/info"
@RequestMapping("/info")
public String getUserInfo() {
return "User Info";
}
}

Beyond just connecting addresses, we will learn about HTTP method mapping in the next chapter, which distinguishes the exact purpose (create, update, delete) of the incoming request.

Advertisement