<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %><!--使用Struts2標籤 -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Input校驗</title>
</head>
<body>
<s:fielderror></s:fielderror><!--顯示Struts2校驗結果 -->
<form action="InputValidate_save.action" method="post">
賬號:<input type="text" name="ID"><br><br>
密碼:<input type="password" name="password"><br><br>
<input type="submit" value="登陸">
</form>
</body>
</html>
<package name="validate" extends="struts-default">
<action name="InputValidate_*" method="{1}" class="com.cb.InputValidate">
<!--Action校驗結果固定返回到input視圖,可以用Struts2標籤來接收 -->
<result name="input">/WEB-INF/page/Inputvaliate.jsp</result>
<result name="success">/WEB-INF/page/SuccessMessage.jsp</result>
</action>
<action name="InputValidate">
<result>/WEB-INF/page/Inputvaliate.jsp</result>
</action>
</package>
package com.cb;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class InputValidate extends ActionSupport {
private String ID;
private String password;
public void setID(String iD) {
ID = iD;
}
public void setPassword(String password) {
this.password = password;
}
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void validate() {//對說有方法進行校驗
if (this.ID == null || "".equals(this.ID.trim())) {
this.addFieldError("ID", "賬號不能爲null");
}
if (this.password == null || "".equals(this.password)) {
this.addFieldError("password", "密碼不能爲null");
} else {
// 如果校驗不成功
if (!Pattern.compile("^1[358]\\d{9}").matcher(this.password).matches()) {
this.addFieldError("password", "密碼格式不正確");
}
}
}
/*public void validateSave() {//只對save方法進行校驗
if (this.ID == null || "".equals(this.ID.trim())) {
this.addFieldError("ID", "賬號不能爲null");
}
if (this.password == null || "".equals(this.password)) {
this.addFieldError("password", "密碼不能爲null");
} else {
// 如果校驗不成功
if (!Pattern.compile("^1[358]\\d{9}").matcher(this.password).matches()) {
this.addFieldError("password", "密碼格式不正確");
}
}
}*/
public String save() {
ActionContext.getContext().put("Msg", "保存成功");
return "success";
}
}