SpringMVC几种接收参数注解
GET请求
- @RequestParam注解:
接收URL上“?”后面的参数,如http://localhost:8080/#/product?xxx
语法:@RequestParam(value=”key”,required=”true/false”,defaultValue=””)
value:key值.
required:是否必须包含参数,默认为true,必须包含的情况下如果发送的请求没有包含会报400.
defaultValue:默认参数值,如果设置了该值,required=true将失效,自动为false,如果没有传该参数,就使用默认值.
/**
* 接收一个参数
* @param id
* @return
*/
@RequestMapping("/test1")
public String test1(@RequestParam String id) {
System.out.println("接收ID:"+id);
return "接收ID:"+id;
}
/**
* 接收多个参数
* @param id
* @return
*/
@RequestMapping("/test2")
public String test2(@RequestParam("id") String id,@RequestParam("username") String username) {
System.out.println("接收ID:"+id+"接收username "+username);
return "接收ID:"+id+"接收username "+username;
}
/**
* required
* defaultValue
* 作用
*/
@RequestMapping("/test3")
public String test3(@RequestParam(value="id",required=true) String id,@RequestParam(value="username",required=false,defaultValue="AllenYang") String username) {
System.out.println("接收ID:"+id+"接收username "+username);
return "接收ID:"+id+"接收username "+username;
}
测试结果
http://localhost/test/test1?id=12
http://localhost/test/test2?id=12&username=小明
http://localhost/test/test3?id=12
http://localhost/test/test3?id=12&username=小明
- @PathVariable注解:
路径拼接传值, @PathVariable 可以将URL中占位符参数{xxx}绑定到处理器类的方法形参中@PathVariable(“xxx“)
如http://localhost/test/xxx,截取方法映射之后路径作为值赋给参数变量
/**
* 传多个参数
* @param id
* @param username
* @return
*/
@RequestMapping(value="/test5/{id}/{username}")
public String test5(@PathVariable("id") String id,@PathVariable("username") String username) {
System.out.println("接收ID:"+id+"接收username "+username);
return "接收ID:"+id+"接收username "+username;
}
测试结果:
http://localhost/test/test5/45/yang
POST请求:
用postman测试的结果