SpringMVC之引數傳遞

KeepTing發表於2017-02-11

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) + "]";
	}

}




相關文章