SpringMVC之参数传递

时间:2022-08-27 21:50:43

1. 通过设置HttpServletRequest request 来获取数据

jsp页面:

<form action="user/add1.do" method="post">
账号:<input type="text" name="userNumber" /><br/>
密码:<input type="text" name="passWord" /><br/>
<input type="submit" value="提交"/>
</form>


后台代码:

@RequestMapping(value="/add1.do")
public String add(HttpServletRequest request){

String userNumber = request.getParameter("userNumber");
String passWord = request.getParameter("passWord");

System.out.println("userNumber:"+userNumber+" passWord:"+passWord);

return "user_add1";
}


2. 直接设置参数add(@RequestParam(value="number")String userNumber,Integer passWord)


jsp页面:

<form action="user/add2.do" method="post">
账号:<input type="text" name="number" /><br/>
密码:<input type="text" name="passWord" /><br/>
<input type="submit" value="提交"/>
</form>

后台代码:

@RequestMapping(value="/add2.do")
public String add(@RequestParam(value="number")String userNumber,Integer passWord){

System.out.println("userNumber:"+userNumber+" passWord:"+passWord);

return "user_add2";
}

3. 通过对象(JavaBean),其中表单的name属性的值必须和类的属性名称一致

jsp页面:

<form action="user/add3.do" method="post">
编号:<input type="text" name="userId" /><br/>
姓名:<input type="text" name="userName" /><br/>
性别:<input type="text" name="userSex" /><br/>
兴趣爱好:
<input type="checkbox" name="userXq" value="英雄联盟"/>英雄联盟
<input type="checkbox" name="userXq" value="DOTA"/>DOTA<br/>
时间:<input type="text" name="userTime" /><br/>
<input type="submit" value="提交"/>
</form>


后台代码:

@RequestMapping(value="/add3.do")
public String add3(UserInfo user){

System.out.println(user);

return "user_add3";
}


JavaBean代码:

public class UserInfo  {

private Integer userId;
private String userName;
private String userSex;
private String[] userXq;

public String[] getUserXq() {
return userXq;
}

public void setUserXq(String[] userXq) {
this.userXq = userXq;
}

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getUserSex() {
return userSex;
}

public void setUserSex(String userSex) {
this.userSex = userSex;
}

@Override
public String toString() {
return "UserInfo [userId=" + userId + ", userName=" + userName
+ ", userSex=" + userSex + ", userXq="
+ Arrays.toString(userXq) + "]";
}

}