struts2对Action中所有的方法进行输入校验

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>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值