DataValidateAction.java:
package blog.validate;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionSupport;
public class DataValidateAction extends ActionSupport {
private static final long serialVersionUID = -1817223356525882414L;
private String user;
private String mobile;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
@Override
public void validate() {
if (this.user == null || "".equals(this.user)) {
this.addFieldError("user", "用户名不能为空");
}
if (this.mobile == null || "".equals(this.mobile)) {
this.addFieldError("mobile", "手机号码不能为空");
}else {
if (!Pattern.compile("^1[358]\\d{9}$").matcher(mobile).matches()) {
this.addFieldError("mobile", "手机号码格式不正确");
}
}
}
public String execute(){
return "success";
}
}
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="validate" extends="struts-default" namespace="/person">
<action name="validate" class="blog.validate.DataValidateAction" method="execute">
<result name="input">/index.jsp</result>
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>校验输入</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<s:fielderror/>
<form action="" method="post" >
用户姓名:<input type="text" name="user"/>不能为空<br/>
手机号码:<input type="text" name="mobile"/>不能为空,并且要符合规则<br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>