@Controller和@RestController的區(qū)別及應(yīng)用
@Controller和@RestController區(qū)別
在springboot開發(fā)中控制層使用注解@Controller時,加有@GetMapping(@PostMapping或@RequestMapping)注解的方法返回值對應(yīng)的是一個視圖,而使用@RestController返回值對應(yīng)的是json數(shù)據(jù),而@Controller+@ResponseBody的作用相當(dāng)于@RestController。
@Controller的應(yīng)用
先在application.properties配置文件中配置
spring.mvc.view.prefix=classpath:/templates/ spring.mvc.view.suffix=.html
然后在控制層CustomerController類的代碼為
@Controller public class CustomerController { @Resource CustomerServiceI customerServiceI; @GetMapping("/") public String index() { return "redirect:/list"; } @GetMapping("/list") public String list(Model model) { List<Customer> users = customerServiceI.getUserList(); model.addAttribute("users",users); return "list"; } }
啟動程序后在瀏覽器輸入localhost:8080/list訪問頁面即為templates文件夾下的list.html
@RestController的應(yīng)用
控制層CustomerController類的代碼為
@RestController public class CustomerController { @Resource CustomerServiceI customerServiceI; @GetMapping("/") public String index() { return "redirect:/list"; } @GetMapping("/list") public List<Customer> list(Model model) { List<Customer> users = customerServiceI.getUserList(); model.addAttribute("users",users); return users; } }
啟動程序后在瀏覽器輸入localhost:8080/list訪問效果如下
@Controller和@RestController區(qū)別的小坑
這兩個的區(qū)別其實是個很簡單的問題,但是對于初學(xué)者可能遇到了會掉坑里。
@RestController注解相當(dāng)于@ResponseBody + @Controller合在一起的作用。
1.如果注解Controller使用@RestController
則Controller中的方法無法返回jsp頁面,或者h(yuǎn)tml,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return 里的內(nèi)容。
代碼如圖:
結(jié)果如圖:
2.如果需要返回到指定頁面(jsp/html)
則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
代碼如圖:
結(jié)果如圖:
如果需要返回JSON,XML或自定義mediaType內(nèi)容到頁面,則需要在對應(yīng)的方法上加上@ResponseBody注解。
代碼如圖:
結(jié)果如圖:
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/chenbingbing111/article/details/81070829