轉載:淺析@PathVariable 和 @RequestParam
在網上看了一篇很好的文章,講的很清楚明了,說到了點子上(轉自:https://blog.csdn.net/chuck_kui/article/details/55506723):
首先 上兩個地址:
地址① http://localhost:8989/SSSP/emps?pageNo=2
地址② http://localhost:8989/SSSP/emp/7
如果想獲取地址①中的 pageNo的值 ‘2’ ,則使用 @RequestParam ,
如果想獲取地址②中的 emp/7 中的 ‘7 ’ 則使用 @PathVariable
獲取地址① 中的‘2’ 使用的 方法是如下:
1 @RequestMapping("/emps")View Code2 public String list(@RequestParam(value="pageNo",required=false, 3 defaultValue="1")String pageNoStr,Map<String, Object>map){ 4 5 int pageNo = 1; 6 try { 7 //對pageNo 的校驗 8 pageNo = Integer.parseInt(pageNoStr); 9 if(pageNo<1){10 pageNo = 1; 11 } 12 } catch (Exception e) { 13 } 14 Page<Employee> page = employeeService.getPage(pageNo, 5); 15 map.put("page",page); 16 17 return "emp/list"; 18 }
獲取地址② 中的 ‘7’ 使用的方法是如下:
1 @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)View Code2 public String edit(@PathVariable("id")Integer id,Map<String , Object>map){ 3 Employee employee = employeeService.getEmployee(id); 4 List<Department> departments = departmentService.getAll(); 5 map.put("employee", employee); 6 map.put("departments", departments); 7 return "emp/input"; 8 }
大道理不講 原理也不分析就記憶一點,那一點呢? 看‘這個符號‘?’
1. 若獲取的入參的 參數 是下面這種形式 就使用 @requestParam 去獲取 參數‘2’
/emps?pageNo=2
2. 若獲取的入參的 參數 是下面這種形式 就使用 @PathVariable 去獲取參數 ‘7’
/emp/7
多說一點
RequestParam 漢語意思就是: 請求參數 顧名思義 就是獲取參數的
PathVariable 漢語意思是:路徑變量,顧名思義,就是要獲取一個url 地址中的一部分值,那一部分呢? RequestMapping 上說明了@RequestMapping(value="/emp/{id}"),我就是想獲取你URL地址 /emp/ 的後面的那個 {id}的。
so,就看‘?’ 若是想獲取 ‘?’ 後面的pageNo 的值 ‘2’, 就使用RequestParam ,
若想獲取的是url 地址的一部分 ‘7’ 就使用PathVariable
@PathVariable是用來獲得請求url中的動態參數的
理論 可看 下面的博文
http://blog.csdn.net/walkerjong/article/details/7946109
@RequestParam @RequestBody @PathVariable 等參數綁定註解詳解
http://dorole.com/tag/uri-template/
http://blog.csdn.net/jaryle/article/details/51851120
@pathvariable和@RequestParam註解的區別
轉載:淺析@PathVariable 和 @RequestParam