【转载】@RestController和@Controller+@Responsebody理解

转载于 https://blog.csdn.net/weixin_42449534/article/details/96737040

如果需要返回的是数据(如:JSON、XML或自定义的metatype等数据类型)时,@RestController完全等同于@Controller+@Responsebody:

  • @RestController:返回的直接是index字符串(优先)
  1. @RestController
  2. public class HelloController {
  3. @Autowired
  4. private GirlProperties girlProperties;
  5. @GetMapping(value = "/hello")
  6. public String say(){
  7. //ModelAndView modelAndView = new ModelAndView("index");
  8. //return modelAndView;
  9. return "index";
  10. }
  11. }
  • @Controller:如果需要返回的是index字符串(JSON、XML等数据类型),则需要在每个方法体里面添加@ResponseBody注解(简单理解为@ResponseBody注解就是标记方法体不调用视图解析器)
  1. @Controller
  2. public class HelloController {
  3. @Autowired
  4. private GirlProperties girlProperties;
  5. @GetMapping(value = "/hello")
  6. @ResponseBody
  7. public String say(){
  8. //ModelAndView modelAndView = new ModelAndView("index");
  9. //return modelAndView;
  10. return "index";
  11. }
  12. }

如果要返回的是jsp、html等页面时两种注解使用方法:

  • @RestController:方法体配合ModelAndView使用
  1. @RestController
  2. public class HelloController {
  3. @Autowired
  4. private GirlProperties girlProperties;
  5. @GetMapping(value = "/hello")
  6. public ModelAndView say(){
  7. ModelAndView modelAndView = new ModelAndView("index");
  8. return modelAndView;
  9. }
  10. }
  • @Controller:可直接返回jsp、index等页面(优先)
  1. @Controller
  2. public class HelloController {
  3. @Autowired
  4. private GirlProperties girlProperties;
  5. @GetMapping(value = "/hello")
  6. public String say(){
  7. //ModelAndView modelAndView = new ModelAndView("index");
  8. //return modelAndView;
  9. return "index";
  10. }
  11. }

 

 

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>demo</title>
  6. </head>
  7. <body>
  8. <h1>Hello Spring Boot!</h1>
  9. </body>
  10. </html>

 

posted @ 2021-10-26 14:17  丨Days丨  阅读(71)  评论(0)    收藏  举报