<%@ 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";
}
}