@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