@RestController/@Controller/@ResponseBody
1) 如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁面,或者html,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內(nèi)容就是Return 里的內(nèi)容。
?
2) 如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
??? 如果需要返回JSON,XML或自定義mediaType內(nèi)容到頁面,則需要在對應的方法上加上@ResponseBody注解。
?
例如:
1.使用@Controller 注解,在對應的方法上,視圖解析器可以解析return 的jsp,html頁面,并且跳轉(zhuǎn)到相應頁面
若返回json等內(nèi)容到頁面,則需要加@ResponseBody注解
?
@CrossOrigin
@Controller
public class FileUploadController {
//跳轉(zhuǎn)到上傳文件的頁面
@RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
public String goUploadImg() {
//跳轉(zhuǎn)到 templates 目錄下的 uploadimg.html
return "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*/ public class HospitalController {//注入Service服務對象@Autowiredprivate HospitalService hospitalService;/*** 查詢所有醫(yī)院信息(未分頁)*/@RequestMapping(value = "findAllHospital",method = RequestMethod.GET)public List<Hospital> findAllHospital(){List<Hospital> hospitalList= hospitalService.findAllHospital();return hospitalList;}總結(jié)
以上是生活随笔為你收集整理的@RestController/@Controller/@ResponseBody的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多线程:Callable
- 下一篇: JNI : Java程序调用C方法