您的位置:首页 > 产品设计 > UI/UE

@params、@PathVariabl和@RequestParam用法与区别

2017-11-15 19:34 453 查看
【1】params

params: 指定request中必须包含某些参数值是,才让该方法处理。

@RequestMapping(value = "testParamsAndHeaders", params = { "username","age!=10" })
public String testParamsAndHeaders() {
System.out.println("testParamsAndHeaders");
return SUCCESS;
}

params 只是判断url 或者 form data 中的参数是否复合params的定义,并不会直接绑定数据到方法的参数中!

【2】@PathVariabl

绑定路径中的占位符参数到方法参数变量中;

只能绑定路径中的占位符参数,且路径中必须有参数。

无论是 GET 或者POST 只要 URL中有参数即可!

如:

GET

Request URL:http://localhost:8080/SpringMVC-1/springmvc/testPathVariable/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>

【注意:】如果URL中无参数,将会出错;如果URL有参数,但是没有使用@PathVariabl该注解,那么URL的参数不会默认与方法参数绑定!方法里的参数会默认绑定表单里面对应的参数!

后台code

如果参数名与占位符一致,则可直接使用@PathVariable;

如果不一致,则在@PathVariable( )括号内绑定占位符。

@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id2) {
System.out.println("testPathVariable: " + id2);
return SUCCESS;
}


【3】@RequestParam

value:参数key,可以不写;

required:默认值为true,可以不写;

获取URL或者 form data 中的参数

GET

<a href="springmvc/testRequestParam?username=atguigu&age=11&sex=boy">


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>

注意 :

GET中的参数形式为:username=atguigu&age=11&sex=boy

POST中的参数形式为:以键值对形式保存在form data
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐