【转载】@RestController和@Controller+@Responsebody理解
转载于 https://blog.csdn.net/weixin_42449534/article/details/96737040
如果需要返回的是数据(如:JSON、XML或自定义的metatype等数据类型)时,@RestController完全等同于@Controller+@Responsebody:
- @RestController:返回的直接是index字符串(优先)
- @RestController
- public class HelloController {
-
- @Autowired
- private GirlProperties girlProperties;
-
- @GetMapping(value = "/hello")
- public String say(){
- //ModelAndView modelAndView = new ModelAndView("index");
- //return modelAndView;
- return "index";
- }
- }
- @Controller:如果需要返回的是index字符串(JSON、XML等数据类型),则需要在每个方法体里面添加@ResponseBody注解(简单理解为@ResponseBody注解就是标记方法体不调用视图解析器)
- @Controller
- public class HelloController {
-
- @Autowired
- private GirlProperties girlProperties;
-
- @GetMapping(value = "/hello")
- @ResponseBody
- public String say(){
- //ModelAndView modelAndView = new ModelAndView("index");
- //return modelAndView;
- return "index";
- }
- }
如果要返回的是jsp、html等页面时两种注解使用方法:
- @RestController:方法体配合ModelAndView使用
- @RestController
- public class HelloController {
-
- @Autowired
- private GirlProperties girlProperties;
-
- @GetMapping(value = "/hello")
- public ModelAndView say(){
- ModelAndView modelAndView = new ModelAndView("index");
- return modelAndView;
- }
- }
- @Controller:可直接返回jsp、index等页面(优先)
- @Controller
- public class HelloController {
-
- @Autowired
- private GirlProperties girlProperties;
-
- @GetMapping(value = "/hello")
- public String say(){
- //ModelAndView modelAndView = new ModelAndView("index");
- //return modelAndView;
- return "index";
- }
- }
index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>demo</title>
-
- </head>
- <body>
- <h1>Hello Spring Boot!</h1>
- </body>
- </html>

浙公网安备 33010602011771号