springMVC常用的两种传参方式
1.使用pojo作为入参:
SpringMVC 会按照请求参数名和POJO属性名进行自动匹配,自动为该对象填充属性值。并支持级联属性。如dept.deptId、dept.address.tel等。表单中的name属性值要与类中的变量名相对应。
2.使用原生ServletAPI作为入参,具体支持一下类型:
HttpServletRequest
HttpServletReponse
java.security.Principal
Locale
InputStream
OutputStream
Reader
Writer
代码
handler
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.sycu.sunqg.entity.userBean;
import jdk.nashorn.internal.ir.RuntimeNode.Request;
@Controller
public class helloWord {
private static final String success = "success";
@RequestMapping("testServletApi")
public String testServletApi(HttpServletRequest request,
HttpServletResponse response) throws IOException{
System.out.print(request + "," +response);
return success;
}
@RequestMapping("testPojo")
public String testPojo(userBean user){
System.out.println(user);
return success;
}
}
userbean
public class userBean {
private String userName;
private String passWord;
private String email;
private Integer 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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "userBean [userName=" + userName + ", passWord=" + passWord + ", email=" + email + ", age=" + age
+ ", address=" + address + "]";
}
}
addressbean
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 + "]";
}
}
jsp
<a href="testServletApi">test servlet</a>
<br>
<form action="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>
city:<input type="text" name="address.city">
<br>
province:<input type="text" name="address.province">
<br>
<input type="submit" value="submit"/>
</form>