淺談 @RequestParam 和@PathVariable

來源:互聯網
上載者:User

標籤:擷取   clear   tps   ice   ora   target   src   Fix   led   

著作權聲明:本文為博主原創文章,如果對你有用,敬請帶走! 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")
  2. public String list(@RequestParam(value="pageNo",required=false,
  3. defaultValue="1")String pageNoStr,Map<String, Object>map){
  4.  
  5. int pageNo = 1;
  6.  
  7. try {
  8. //對pageNo 的校正
  9. pageNo = Integer.parseInt(pageNoStr);
  10. if(pageNo<1){
  11. pageNo = 1;
  12. }
  13. } catch (Exception e) {}
  14.  
  15. Page<Employee> page = employeeService.getPage(pageNo, 5);
  16. map.put("page",page);
  17.  
  18. return "emp/list";
  19. }

擷取地址② 中的 ‘7’ 使用的方法是如下:

 

  1. @RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
  2. 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註解的區別

 

 

 

淺談 @RequestParam 和@PathVariable

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.