【SpringBoot】@Controller和@RestController的区别

@RestController = @ResponseBody + @Controller

使用@RestController,return返回的是响应体,例如如果return "success",则会在页面上显示success

使用@Controller,return返回的是html页面,例如如果return "success",则会跳转到页面success.html

如果在一个控制器类中,希望某些方法的return实现跳转,某些方法的return可以返回响应体,就可以使用Controller注解,并且在需要返回响应体的方法上加上@ResponseBody的注解

 1 @Controller
 2 public class HelloController {
 3 
 4     @ResponseBody
 5     @RequestMapping("/hello")
 6     public String hello() {
 7         return "hello";
 8     }
 9 
10     @RequestMapping("/success")
11     public String success(Map<String,Object> map){
12         map.put("successful","成功");
13         return "success";
14     }
15 }

success.html

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>success</title>
 6 </head>
 7 <body>
 8     <h1>
 9         成功
10     </h1>
11     <div th:text="${successful}"></div>
12 </body>
13 </html>

hello.html

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>hello</title>
 6 </head>
 7 <body>
 8 <h1>跳转到hello页面</h1>
 9 </body>
10 </html>

从下面的截图可以看出,加了response注解的直接显示响应体,而没有跳转到hello.html

 

posted @ 2020-06-18 11:25  xd会飞的猫  阅读(311)  评论(0编辑  收藏  举报