在处理方法入参使用@RequestParam可以把请求参数传递给请求方法,@RequestParam包含的属性值:
--- value :参数名称
--- required :是否必须,默认为true,表示请求参数中必须包含对应的参数,否则抛出异常。
--- defaultValue:当请求参数缺少或者有请求参数但值为空时,值采用该设置值。
示例:
1)在HelloWord.java中添加testRequestParam方法:
package com.dx.springlearn.handlers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("class_requestmapping")
public class HelloWord {
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") int age) {
System.out.println("testRequestParam, username: " + username + ",address: " + address + ",age: " + age);
return SUCCESS;
}
}
2)在index.jsp中插入链接html:
<a
href="class_requestmapping/testRequestParam?username=abc&address=def&age=26">testRequestParam</a>
<br>
3)测试。
打印信息为:testRequestParam, username: abc,address: def,age: 26
抛出异常:
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