@ResponseBody

 
 
1. The function of the @responseBody annotation is to convert the object returned by the controller method into the specified format through an appropriate converter, and then write it to the body area of ​​the response object. It is usually used to return JSON data or XML data. Note that Well, after using this annotation, you will not go to the processor, but directly write the data to the input stream. Its effect is equivalent to outputting the data in the specified format through the response object.
 
 2. Code example
 @RequestMapping("/login")
   @ResponseBody
 public User login(User user){  
  return user;
     }
 
User field: userName pwd
Then the data received in the foreground is: '{"userName":"xxx","pwd":"xxx"}'
 
The effect is equivalent to the following code:
@RequestMapping("/login")
public void login(User user, HttpServletResponse response){
  response.getWriter.write(JSONObject.fromObject(user).toString());
}
 
3. Common mistakes
spring boot + thymeleaf 报错 org.thymeleaf.exceptions.TemplateInputException
The above error is a low-level error. We all know that annotating @Controller and @RestController on the controller can tune the interface on the front end, but the difference between the two is that when the former is used, the method must be annotated @ResponseBody, If you do not add @ResponseBody, the above error will be reported, because when the @Controller annotation is used, the default method of spring returns the view object (page). With @ResponseBody, the method returns a specific object. The role of @RestController is equivalent to the combination of @Controller+@ResponseBody

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324777547&siteId=291194637