@ResponseBody

 
 
1、@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据,需要注意的呢,在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
 
 2.代码示例
 @RequestMapping("/login")
   @ResponseBody
 public User login(User user){  
  return user;
     }
 
User字段:userName pwd
那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'
 
效果等同于如下代码:
@RequestMapping("/login")
public void login(User user, HttpServletResponse response){
  response.getWriter.write(JSONObject.fromObject(user).toString());
}
 
3、常见错误
spring boot + thymeleaf 报错 org.thymeleaf.exceptions.TemplateInputException
以上错误,是个低级错误,我们都知道,在controller上加注解@Controller 和@RestController都可以在前端调通接口,但是二者的区别在于,当用前者的时候在方法上必须添加注解@ResponseBody,如果不添加@ResponseBody,就会报上面错误,因为当使用@Controller 注解时,spring默认方法返回的是view对象(页面)。而加上@ResponseBody,则方法返回的就是具体对象了。@RestController的作用就相当于@Controller+@ResponseBody的结合体

猜你喜欢

转载自www.cnblogs.com/zhangjunlong/p/8929867.html