使用@RequestParam可以将URL中的请求参数,绑定到方法的入参上,并通过@RequestParam的3个参数进行配置
Modifier and Type | Optional Element | Description |
String | defaultValue | 方法入参默认值 |
boolean | required | 是否必须包含该参数,默认为true |
String | value | 请求参数名 |
其实不使用@RequestParam,SpringMVC也会将request的parameter自动绑定到method的parameter中,
使用@RequestParam只不过是对parametr进行配置,和对URL更精确化的配置
代码:
1: @RequestMapping("/testRequestParam")2: @Controller
3: public class TestRequestParam {4: private static final String SUCCESS = "success";5:
6: /*7: * 使用@RequestParam绑定入参,并进行配置8: *9: * 当请求为:testRequestParam/user?name=zs&age=200时10: * 输出结果:name = zs class = j1001 age = 20011: *12: * 当请求为:testRequestParam/user?name=zs&age=200&class=j111时13: * 输出结果:name = zs class = j111 age = 20014: * */15: @RequestMapping("/user")16: public String testParam(@RequestParam(value = "name") String name,17: @RequestParam(value = "class", required = false, defaultValue = "j1001") String cla,18: Integer age) {
19: System.out.println("name = " + name + " class = " + cla + " age = " + age);20: return SUCCESS;21: }
22: }
URL:
1: <a href="testRequestParam/user?name=zs&age=200&class=j111"> name=zs age=200 class=j1111 输入name、age、class</a>2:
3: <br/><br/>4: <a href="testRequestParam/user?name=zs&age=200"> name=zs age=200 只输入name和age不输入class</a>5:
6: <br/><br/>