1.使用@RequestParam来绑定请求参数,代码如下:
<a href="TestRequestMapping/TestRequestParam?username=username&age=10">TestRequestParam</a>
/**
* 使用@RequestParam绑定请求参数
* @param username
* @param age
* @return
* value 表示请求参数的名称
* required 表示该参数是否必须(true或者false)
* defaultValue 表示该参数的默认值
*/
@RequestMapping("TestRequestParam")
public String testRequestParam(@RequestParam(value="username",required=false,defaultValue="zhangsan") String username,
@RequestParam(value="age") Integer age)
{
System.out.println("username:"+username+" "+"age=:"+age);
return "success";
}
其中:
value 表示请求参数的名称
required 表示该参数是否必须(true或者false)
defaultValue 表示该参数的默认值
此外,还可以用@RequestHeader来映射请求头以及@CookieValue来映射Cookie值,用法与@RequestParam相同
2.使用POJO对象绑定请求参数
SpringMVC会按照请求参数名和POJO属性名进行自动的匹配,自动为该对象填充属性,例如User.address、User.name等,且支持级联属性
代码如下:
首先先写两个POJO类
/**
* User实体类
* @author YZX
*
*/
public class User {
private String userName;
private String password;
private String email;
private int age;
private Address address;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "User [userName=" + userName + ", password=" + password
+ ", email=" + email + ", age=" + age + ", address=" + address
+ "]";
}
}
/**
* Address实体类
* @author YZX
*
*/
public class Address {
private String province;
private String city;
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Address [province=" + province + ", city=" + city + "]";
}
}
接着写一个表单用于发送请求
<form action="TestRequestMapping/TestPojo" method="post">
username:<input type="text" name="userName">
<br>
password:<input type="password" name="password">
<br>
email:<input type="text" name="email">
<br>
age:<input type="text" name="age">
<br>
province:<input type="text" name="address.procince">
<br>
city:<input type="text" name="address.city">
<br>
<input type="submit" value="Submit">
</form>
编写一个方法用于响应请求
@RequestMapping("TestPojo")
public String testPojo(User user)
{
System.out.println(user);
return "success";
}
从上述可以看出,该方法传入了一个User类作为参数,而表单中的userName,password,email,age均为User的属性,而provider以及city则为User类的address属性的属性。但要注意,请求参数名必须与POJO的属性名相同才能自动匹配,否则会出现错误。
3.使用Servlet原生的API作为请求参数
可以使用Servlet原生API作为目标方法的参数:
①HttpServletReque
②HttpServletResponse
③HttpSession
④java.security.principal
⑤Reader
⑥Writer