@Controller和@RestController的區(qū)別?

@RestController注解相當于@ResponseBody + @Controller合在一起的作用

1)如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁面,配置的視圖解析器InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return 里的內(nèi)容。

例如:本來應該到success.jsp頁面的,則其顯示success.

2)如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。

3)如果需要返回JSON,XML或自定義mediaType內(nèi)容到頁面,則需要在對應的方法上加上@ResponseBody注解。


例如:

1.使用@Controller 注解,

在對應的方法上,視圖解析器可以解析return 的jsp,html頁面,并且跳轉(zhuǎn)到相應頁面

若返回json等內(nèi)容到頁面,則需要加@ResponseBody注解

@CrossOrigin

@Controllerpublicclass FileUploadController {//跳轉(zhuǎn)到上傳文件的頁面@RequestMapping(value="/gouploadimg", method = RequestMethod.GET)public String goUploadImg() {//跳轉(zhuǎn)到 templates 目錄下的 uploadimg.htmlreturn"uploadimg";

}//處理文件上傳@RequestMapping(value="/testuploadimg", method = RequestMethod.POST)public@ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,

HttpServletRequest request) {

System.out.println("調(diào)用文件上傳方法");

String contentType = file.getContentType();

String fileName = file.getOriginalFilename();


??2.@RestController注解

相當于@Controller+@ResponseBody兩個注解的結(jié)合,返回json數(shù)據(jù)不需要在方法前面加@ResponseBody注解了,但使用@RestController這個注解,就不能返回jsp,html頁面,視圖解析器無法解析jsp,html頁面

@CrossOrigin

@RestController /* @Controller + @ResponseBody*/publicclass HospitalController {

? ? //注入Service服務對象? ? @Autowired

? ? private HospitalService hospitalService;

? ? /**? ? * 查詢所有醫(yī)院信息(未分頁)

? ? */? ? @RequestMapping(value = "findAllHospital",method = RequestMethod.GET)

? ? publicList findAllHospital(){

? ? ? ? List hospitalList= hospitalService.findAllHospital();

? ? ? ? return hospitalList;

? ? }

轉(zhuǎn)自:https://www.cnblogs.com/clwydjgs/p/9255046.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容