SoFunction
Updated on 2025-04-13

The use and difference between @RestController and @Controller in Spring

Use and differences between @RestController and @Controller in Spring

@RestControlleryesSpring WebA key annotation provided for the development of RESTful Web services is@Controllerand@ResponseBodyCombination annotations. pass@RestController, we can implement processing HTTP requests and directly return data in JSON, XML, or other formats, instead of returning to the view page.

The following is correct@RestControllerDetailed analysis of the annotations:

1. Basic definition

@RestControllerThe role of

  • It's aTag classannotation to identify that class is aSpring MVC Controller, and the return values ​​of all methods will be directly used as the HTTP response body.
  • Can be used to simplify the development of RESTful API.

Source of the annotation

@RestControllerIt was introduced in Spring 4.0 and belongs toBag.

Combination relationship

It's equivalent to@Controllerand@ResponseBodyCombination:

@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
}

@Controller

  • Identifies the current class as a Spring MVC controller that handles HTTP requests.

@ResponseBody

  • The return value of the method is not parsed into the view name, but is written directly into the HTTP response body.

2. Usage scenarios

@RestControllerIt is generally used to develop RESTful-style service interfaces. For example, in projects separated by front-end, back-end, the front-end calls the back-end interface through AJAX or other Http clients to obtain JSON or XML data.

and@ControllerThe difference is:

  • @RestControllerFocus on returning data (such as JSON, XML).
  • @ControllerUsually used to return view pages (such as HTML, JSP).

3. Use examples

Example 1: Create a simple RESTful API

import .*;

@RestController
@RequestMapping("/api/users")
public class UserController {

    // GET request to obtain user information    @GetMapping("/{id}")
    public String getUserById(@PathVariable("id") Long id) {
        return "User ID: " + id;
    }

    // POST request to create a new user    @PostMapping
    public String createUser(@RequestBody String user) {
        return "User created: " + user;
    }
}

Request instructions

  1. @RestControllerMarkedUserControllerThis class is a RESTful controller.
  2. The return value is written directly to the response body without additional use@ResponseBody
  3. Two interfaces are implemented in the example:
    • Obtain user information (GET /api/users/{id})。
    • Create a user (POST /api/users)。

4. Comparison with @Controller

characteristic @RestController @Controller
Main uses Process RESTful Web Service Requests, Returning JSON or XML Return to the view page (such as Thymeleaf, JSP, etc.).
Do you need to use @ResponseBody No, the default is applied to all method return values. Each method needs to be labeled separately by @ResponseBody.
Return to content Data (JSON, XML, text, etc.). View name (such as an Html file).
Use scenarios Projects separated from front and back ends. Traditional web applications (such as returning to HTML pages).

Example comparison:

@RestControllerExample

@RestController
@RequestMapping("/api")
public class ApiController {
    @GetMapping("/greeting")
    public String greeting() {
        return "Hello, World!";
    }
}

Return result:Hello, World!As a plain text response.

@ControllerExample

@Controller
@RequestMapping("/web")
public class WebController {
    @GetMapping("/greeting")
    public String greeting() {
        return "greeting"; // Return to the view name    }
}

Return result: The render name isview.

5. Common annotations are used in conjunction with

5.1 Cooperation@RequestMapping

@RequestMappingThe request path used to specify a class or method. Can be with@RestControllerUse with it, set the basic path to the RESTful API.

Example:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, API!";
    }
}

Request path:GET /api/hello

5.2 Cooperation@GetMapping@PostMapping

  • @GetMapping: Used to handle HTTP GET requests.
  • @PostMapping: Used to handle HTTP POST requests.

Example:

@RestController
@RequestMapping("/users")
public class UserController {

    // GET request    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return "User ID: " + id;
    }

    // POST request    @PostMapping
    public String createUser(@RequestBody String user) {
        return "Created User: " + user;
    }
}

5.3 Cooperation@RequestBody

@RequestBodyConverts the JSON request body to a Java object.

Example:

@RestController
@RequestMapping("/books")
public class BookController {

    @PostMapping
    public String createBook(@RequestBody Book book) {
        return "Created Book: " + ();
    }
}
class Book {
    private String title;
    private String author;
    // Getter and Setter
}

Request data:

{
    "title": "Spring in Action",
    "author": "Craig Walls"
}

5.4 Cooperation@PathVariableand@RequestParam

  • @PathVariable: Get variables from the request path.
  • @RequestParam: Get the value from the query parameters.

Example:

@RestController
@RequestMapping("/products")
public class ProductController {

    @GetMapping("/{id}")
    public String getProduct(@PathVariable Long id, @RequestParam String name) {
        return "Product ID: " + id + ", Name: " + name;
    }
}
  • Request path:GET /products/123?name=Phone
  • Return result:Product ID: 123, Name: Phone

6. Return JSON data

@RestControllerBy default, the return value is serialized to JSON format (if dependentJacksonstock exists).

Example:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "John");
    }
}
class User {
    private Long id;
    private String name;
    // Constructor, Getter, Setter
}

Return result:

{
    "id": 1,
    "name": "John"
}

7. FAQ

7.1 The return value cannot be serialized

  • If the returned object is not providedgetterOr the absence of a parameterless constructor may cause JSON serialization to fail.
  • Solution: Make sure the returned object is correctgetterand parameterless constructor.

7.2 404 Not Foundmistake

  • Check that the request path is correct.
  • Ensure the controller class and method@RequestMappingPath matching.

7.3 415 Unsupported Media Typequestion

  • If using@RequestBody, make sure there is a request headerContent-Type: application/json

8. Feature summary

characteristic describe
Combination annotation is a combination of @Controller and @ResponseBody.
Return to data format Returns JSON data by default (requires dependence on the Jackson library).
Applicable scenarios RESTful API development, front-end and back-end separation project interface development.
Simplify development No additional @ResponseBody is required for each method.

Summarize

  • @RestControllerIt is a convenient annotation provided by Spring Web, dedicated to handling RESTful API requests.
  • It simplifies the traditional@Controller + @ResponseBodydevelopment method.
  • Cooperate with other annotations (e.g.@RequestMapping@GetMapping@RequestBody) Can quickly develop robust RESTful services.
  • In applications where front and back end separation,@RestControllerIt is one of the essential tools.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.