環境:Eclipse 4.3.2、JDK 1.7_45、MySQL 5.0+。採用 Struts2 內建驗證機制 (validate() 方法) 實現登錄表單校驗。
<%@ taglib uri="/struts-tags" prefix="s"%>
<html><body>
<center>請登錄
<!-- 顯示 Action 中 addActionError 的全局錯誤 -->
<s:actionerror/>
<s:form action="LoginAction.action" method="post">
<s:label value="用戶名:" />
<s:textfield name="userName" /><br/>
<s:label value="密碼" />
<s:textfield name="userPwd" /><br/>
<s:submit value="登錄" />
</s:form>
</center>
</body></html>
<struts>
<constant name="struts.ui.theme" value="simple" />
<package name="default" namespace="/" extends="struts-default">
<action name="LoginAction" class="com.tikitoo.action.LoginAction">
<result name="success">/index.jsp</result>
<result name="input">/login.jsp</result> <!-- 驗證失敗返回 -->
</action>
</package>
</struts>
public class LoginAction extends ActionSupport {
private String userName, userPwd;
@Override
public String execute() throws Exception {
UserInfoService service = new UserInfoServiceImpl();
boolean flag = service.loginByUserNameAndUserPwd(userName, userPwd);
if (flag) {
this.addFieldError("true", "登錄成功"); // 也可用 addActionError
return "success";
} else {
this.addActionError("用戶名或密碼不正確!");
return "input";
}
}
@Override
public void validate() {
// 校驗用戶名非空
if (userName == null || "".equals(userName.trim())) {
this.addFieldError("userName", "用戶名不能為空");
}
// 校驗密碼非空
if (userPwd == null || "".equals(userPwd.trim())) {
this.addFieldError("userPwd", "密碼不能為空");
}
}
// getter/setter 省略
}
validate() 方法在 execute() 前自動調用,返回 input 時跳轉至 struts.xml 配置的 input 結果頁面。addFieldError(fieldName, msg):字段級錯誤,JSP 用 <s:fielderror/> 顯示 (需 theme 不為 simple) 或 <s:fielderror fieldName="userName"/> 指定字段。addActionError(msg):全局錯誤,JSP 用 <s:actionerror/> 顯示。struts.ui.theme=simple 時,<s:fielderror/> 不會自動渲染,需手動遍歷 fieldErrors Map 顯示。index.jsp。