@RequestParam @RequestBody @PathVariable 等参数绑定注解详解

转载自: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’ 使用的 方法是如下

[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.         //对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’ 使用的方法是如下:

[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


多说一点,拽一下奋斗

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注解的区别

猜你喜欢

转载自blog.csdn.net/huangchunxia_1/article/details/79872486