Detailed explanation of parameter binding annotations such as @RequestParam @RequestBody @PathVariable

Reprinted from: https://blog.csdn.net/chuck_kui/article/details/55506723

First two addresses:

Address①http://localhost:8989/SSSP/emps?pageNo=2

address②http://localhost:8989/SSSP/emp/7

If you want to get the value '2' of pageNo in address ①, use @RequestParam ,

If you want to get '7' in emp/7 in address ② use @PathVariable


The method used to obtain '2' in address ① is as follows

[java]  view plain copy  
  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.         //Check for 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. }  

The method used to obtain '7' in address ② is as follows:

[java]  view plain copy  
  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


多说一点,拽一下struggle

RequestParam  汉语意思就是: 请求参数 顾名思义 就是获取参数的 

PathVariable 汉语意思是:路径变量,顾名思义,就是要获取一个url 地址中的一部分值,那一部分呢? RequestMapping 上说明了@RequestMapping(value="/emp/{id}"),我就是想获取你URL地址 /emp/ 的后面的那个 {id}的。


so,就看‘?’ 若是想获取 ‘?’ 后面的pageNo 的值 ‘2’, 就使用RequestParam ,

若想获取的是url 地址的一部分 ‘7’ 就使用PathVariable 

embarrassment

@PathVariable is used to obtain dynamic parameters in the request url

The theory can be found in the following blog post

http://blog.csdn.net/walkerjong/article/details/7946109   

Detailed explanation of parameter binding annotations such as @RequestParam @RequestBody @PathVariable

http://dorole.com/tag/uri-template/

http://blog.csdn.net/jaryle/article/details/51851120        The difference between @pathvariable and @RequestParam annotations

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325509109&siteId=291194637