Use and differences between @RestController and @Controller in Spring
@RestController
yesSpring WebA key annotation provided for the development of RESTful Web services is@Controller
and@ResponseBody
Combination 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@RestController
Detailed analysis of the annotations:
1. Basic definition
@RestController
The 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
@RestController
It was introduced in Spring 4.0 and belongs toBag.
Combination relationship
It's equivalent to@Controller
and@ResponseBody
Combination:
@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
@RestController
It 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@Controller
The difference is:
-
@RestController
Focus on returning data (such as JSON, XML). -
@Controller
Usually 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:
-
@RestController
MarkedUserController
This class is a RESTful controller. - The return value is written directly to the response body without additional use
@ResponseBody
。 - Two interfaces are implemented in the example:
- Obtain user information (
GET /api/users/{id}
)。 - Create a user (
POST /api/users
)。
- Obtain user information (
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:
@RestController
Example:
@RestController @RequestMapping("/api") public class ApiController { @GetMapping("/greeting") public String greeting() { return "Hello, World!"; } }
Return result:Hello, World!
As a plain text response.
@Controller
Example:
@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
@RequestMapping
The request path used to specify a class or method. Can be with@RestController
Use 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
@RequestBody
Converts 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@PathVariable
and@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
@RestController
By default, the return value is serialized to JSON format (if dependentJackson
stock 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 provided
getter
Or the absence of a parameterless constructor may cause JSON serialization to fail. - Solution: Make sure the returned object is correct
getter
and parameterless constructor.
7.2 404 Not Found
mistake
- Check that the request path is correct.
- Ensure the controller class and method
@RequestMapping
Path matching.
7.3 415 Unsupported Media Type
question
- 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
-
@RestController
It is a convenient annotation provided by Spring Web, dedicated to handling RESTful API requests. - It simplifies the traditional
@Controller
+@ResponseBody
development method. - Cooperate with other annotations (e.g.
@RequestMapping
、@GetMapping
、@RequestBody
) Can quickly develop robust RESTful services. - In applications where front and back end separation,
@RestController
It 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.