@RequestMapping的簡單理解


@Controller
public class ItemController {
    @Autowired
    private ItemService itemService;
    獲取路徑參數.../item/*
    @RequestMapping("/item/{itemId}")
    @ResponseBody
//    HTTP Status 404 - /WEB-INF/jsp/item/536563.jsp
//    和晶晶的正相反,應該是導入數據庫的問題
//    出現了manager的pom.xml文件忘記添加依賴common了
//此版本還刪除了common中的一些包com.taotao.common,在commom的java包下,晶晶版保留
//    @PathVariable是從路徑中取參數
    public TbItem getItemById(@PathVariable Long itemId) {
        TbItem tbItem = itemService.geTbItemById(itemId);
        return tbItem;
    }
}
    /**
     * 一般為首頁/ */
    @RequestMapping("/")
    public String showIndex() {
        return "index";
    }
    /**
     * 只要下面haha刪除對應位置自定義名稱一致就行,隨便命名
     * @param page
     * @return
     */
    @RequestMapping("/{haha}")
    public String showpage(@PathVariable String haha) {
        return haha;
    }

 

知識點:@RestController注解相當於@ResponseBody + @Controller合在一起的作用。

 

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

 

2) 如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
    如果需要返回JSON,XML或自定義mediaType內容到頁面,則需要在對應的方法上加上@ResponseBody注解。

 

例如:

1.使用@Controller 注解,在對應的方法上,視圖解析器可以解析return 的jsp,html頁面,並且跳轉到相應頁面

若返回json等內容到頁面,則需要加@ResponseBody注解

 

@CrossOrigin
@Controller
public class FileUploadController {

//跳轉到上傳文件的頁面
@RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
public String goUploadImg() {
//跳轉到 templates 目錄下的 uploadimg.html
return "uploadimg";
}

 



//處理文件上傳

@RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
HttpServletRequest request) {
System.out.println("調用文件上傳方法");
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();

 

 

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

 

@CrossOrigin
@RestController /* @Controller + @ResponseBody*/
public class HospitalController {

    //注入Service服務對象
    @Autowired
    private HospitalService hospitalService;

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

    @RequestMapping(value = "findAllHospital",method = RequestMethod.GET)
    public  List<Hospital> findAllHospital(){
        List<Hospital> hospitalList= hospitalService.findAllHospital();
        return hospitalList;
    }
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM