SpringMVC注解之@RequestParam与@PathVariable
在SpringMVC中有俩个注解是可以启到把request中的参数值传递到contorller中参数的,这俩个注解分别是@RequestParam和@PathVariable,但俩者之间还是存在一些区别的
1.使用@PathVariable传递参数时的例子
jsp中的内容
<a href="request/1/testRest.act">testRestGet</a>
controller中的内容
@RequestMapping(value="/{id}/testRest",method=RequestMethod.GET)
public String testRestGet(@PathVariable Integer id){
return "success";
}
2.使用@RequestParam传递参数时的例子
jsp中的内容
<a href="request/testRequestParam.act?username=wujintao&age=21">testRequestParam</a>
controller中的内容
@RequestMapping(value="/testRequestParam",method=RequestMethod.GET)
public String testRequestParam(@RequestParam (value="username")String username
,@RequestParam (value="age",required=false,defaultValue="0")Integer age){
return "success";
}
3. 在使用@RequestParam传递参数时需要注意以下几个点
1.当向controller中传递参数时如果controller中需要传俩个参数,但是我们在jsp中只向controller中传递了一个参数,那么我们需要在@RequestParam中添加required属性值设为false,如果类型是INT型需要在添加一个属性defaultvalue然后设定一个默认值,如果类型为Integer则不需要设置默认值
4.@RequestParam和@PathVariable俩者之间的区别
在使用@RequestParam注解时,url是这样的:http://localhost:8080/test/request?参数名=参数值
在使用@PathVariable注解时,url是这样的:http://localhost:8080/test/request/参数值