在处理方法入参使用@RequestParam可以把请求参数传递给请求方法,@RequestParam包含的属性值:
--- value :参数名称
--- required :是否必须,默认为true,表示请求参数中必须包含对应的参数,否则抛出异常。
--- defaultValue:当请求参数缺少或者有请求参数但值为空时,值采用该设置值。
示例:
1)在HelloWord.java中添加testRequestParam方法:
packagecom.dx.springlearn.handlers;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("class_requestmapping")public classHelloWord {private static String SUCCESS = "success";
@RequestMapping("/testRequestParam")public String testRequestParam(@RequestParam(value = "username") String username,
@RequestParam(value= "address") String address,
@RequestParam(value= "age", required = false, defaultValue = "0") intage) {
System.out.println("testRequestParam, username: " + username + ",address: " + address + ",age: " +age);returnSUCCESS;
}
}
2)在index.jsp中插入链接html:
testRequestParam
3)测试。
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def&age=26
打印信息为:testRequestParam, username: abc,address: def,age: 26
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def&age=
抛出异常:
Jan 04, 2018 8:02:53 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleTypeMismatch
警告: Failed to bind request element: org.springframework.beans.TypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException:
For input string: ""
解决方案,把age定义类型修改为Integer
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc&address=def
打印信息为:testRequestParam, username: abc,address: def,age: 0
当请求url为:http://localhost:8080/SpringMVC_01/class_requestmapping/testRequestParam?username=abc
抛出异常:
HTTP Status 400 - Required String parameter 'address' is not present