1. 程式人生 > >表單+回顯

表單+回顯

一、簡介

1、struts表單效驗時會把提交的內容封裝成bean存放在request域中,存放的關鍵字是UserFormBean

2、效驗 錯誤後會跳轉回提交表單頁面

二、例項

bean之Gender

public enum Gender {
	MALE("male","男"),FEMALE("female","女");
	private String name;
	private String value;
	private Gender(String name,String value) {
		this.name=name;
		this.value=value;
	}
	public String getName() {
		return name;
	}
	public String getValue() {
		return value;
	}
}
bean之Preference
public enum Preference {
	SING("sing","唱歌"),DANCE("dance","跳舞");
	private String name;
	private String value;
	private Preference(String name,String value) {
		// TODO Auto-generated constructor stub
		this.name=name;
		this.value=value;
	}
	public String getName() {
		return name;
	}
	public String getValue() {
		return value;
	}	
}
form表單
  <form action="${pageContext.request.contextPath}/Register.do" method="post">
  	<table>
  		<tr>
  			<td>使用者名稱</td>
  			<td>
  				<input type="text" name="username" value="${UserFormBean.name}">
  			</td>
  		</tr>
  		<tr>
  			<td>密碼</td>
  			<td>
  				<input type="password"  name="password" value="${UserFormBean.password}">
  			</td>
  		</tr>
  		<tr>
  			<td>確認密碼</td>
  			<td>
  				<input type="password"  name="password">
  			</td>
  		</tr>
  		<tr>
  			<td>性別</td>
  			<td>
  				<c:forEach var="gender" items="<%=Gender.values()%>">
  					<input type="radio"  name="gender" value="${gender.name}">${gender.value}
  				</c:forEach> 				
  			</td>
  		</tr>
  		<tr>
  			<td>愛好</td>
  			<td>
  				<c:forEach var="pre" items="<%=Preference.values()%>">
  					<input type="checkbox"  name="preference" value="${pre.name}" ${fn:contains(fn:join(UserFormBean.preference,","),pre.name)?checked:''}>${pre.value}
  				</c:forEach> 				
  			</td>
  		</tr>
  		<tr>
  			<td>城市</td>
  			<td>
  				<select name="city">
  					<option ${UserFormBean.city=='beijing'?selected:''}>北京</option>
  					<option ${UserFormBean.city=='shanghai'?selected:''}>上海</option>
  				</select>				 								
  			</td>
  		</tr>
  		<tr>
  			<td>
  				<input type="submit" value="註冊">
  			</td>
  		</tr>
  	</table>
  </form>
config檔案
	<action-mappings>
 		<action path="/Register" 
				type="action.Register" 
				name="UserFormBean"									
				scope="request"
				validate="true"
				input="/Register.jsp">	
		</action>				
	</action-mappings>