【1】params
params: 指定request中必須包含某些參數值是,才讓該方法處理。
@RequestMapping(value = "testParamsAndHeaders", params = { "username","age!=10" }) public String testParamsAndHeaders() { System.out.println("testParamsAndHeaders"); return SUCCESS; }
- 1
- 2
- 3
- 4
- 5
params 只是判斷url 或者 form data 中的參數是否復合params的定義,並不會直接綁定數據到方法的參數中!
【2】@PathVariabl
-
綁定路徑中的占位符參數到方法參數變量中;
-
只能綁定路徑中的占位符參數,且路徑中必須有參數。
無論是 GET 或者POST 只要 URL中有參數即可!
如:
- GET
Request URL:http://localhost:8080/SpringMVC-1/springmvc/testPathVariable/1
- 1
- POST
<form action="springmvc/testPathVariable/1" method="POST"> <input type="text" name="username" value=""/> <input type="text" name="age" value=""/> <input type="text" name="sex" value=""/> <input type="submit" value="submit"/> </form>
- 1
- 2
- 3
- 4
- 5
- 6
【注意:】如果URL中無參數,將會出錯;如果URL有參數,但是沒有使用@PathVariabl該注解,那么URL的參數不會默認與方法參數綁定!方法里的參數會默認綁定表單里面對應的參數!
- 后台code
如果參數名與占位符一致,則可直接使用@PathVariable;
如果不一致,則在@PathVariable( )括號內綁定占位符。
@RequestMapping("/testPathVariable/{id}") public String testPathVariable(@PathVariable("id") Integer id2) { System.out.println("testPathVariable: " + id2); return SUCCESS; }
- 1
- 2
- 3
- 4
- 5
【3】@RequestParam
-
value:參數key,可以不寫,默認為”“;
-
name:和value作用一樣;
-
required:默認值為true,可以不寫;
-
獲取URL或者 form data 中的參數
- GET
<a href="springmvc/testRequestParam?userName=tom&age=11&sex=boy">
- 1
- POST
<form action="springmvc/testRequestParam" method="POST"> <input type="text" name="userName" value=""/> <input type="text" name="age" value=""/> <input type="text" name="sex" value=""/> <input type="submit" value="submit"/> </form>
- 1
- 2
- 3
- 4
- 5
- 6
注意 :
GET中的參數形式為:username=tom&age=11&sex=boy
POST中的參數形式為:以鍵值對形式保存在form data
后台:
@RequestMapping(value="/regist",produces="application/json;charset=utf-8") @ResponseBody public String regist(SysUser sysUser , @RequestParam(required=true,name="sex") String sex){ String userName = sysUser.getUserName(); String age = sysUser.getAge(); //... return "regist success"; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
總得來說,均是鍵值對形式。與@PathVariabl中的占位符形式不同!!!
原文鏈接 : https://blog.csdn.net/j080624/article/details/56280382