如何对应用中action中的方法进行校验(代码方式)

一.对所有方法进行校验

1.action继承ActionSuppor类,重写validate方法。

public class personAction extends ActionSupport{

	/**通过代码方式对所有action进行校验
	 * test:对页面上的用户名称和用户密码进行有效性校验*/
	
	private String telephone;
	
	private String message;
	
	
	public String getMessage() {
		return message;
	}


	public void setMessage(String message) {
		this.message = message;
	}

	public String getTelephone() {
		return telephone;
	}


	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	
	public String save()
	{
		message = "保存成功";//如果校验不通过,不会执行这行语句,返回的result也不是"success",而是"input"
		return "success" ;
	}


	@Override
	public void validate() {
		if(telephone == null || telephone.trim().equals(""))
		{
			this.addFieldError("telephoneNull", "手机号码为空");
		}
		
		else if(!Pattern.compile("^1[358]\\d{9}$").matcher(telephone).matches())
		{
			this.addFieldError("telephoneError", "手机号码不符合规范");
		}
	}

}

2.在.xml配置文件中配置如下信息
<!--通过代码对所有action进行有效性校验  -->
<action name = "validate_*" class = "com.action.personAction" method = "{1}">
    <result name="input">/index.jsp</result>
    <result name = "success">/WEB-INF/page/validate.jsp</result>
</action>
  如果校验不通过,fieldErrors中存在校验失败信息,struts2会将请求转发到name为input的result。不提供input的result,如果有this.addFieldError("xxxError", "xxx")操作,程序会报:No result defined for action com.action.personAction and result input


3.jsp调用
 <form action ="<%=request.getContextPath() %>/department/validate_save.action" method = "post">
   电话号码:<input type = "text" name = "telephone"><br/>
   	    <input type = "submit" value="提交">
 </form>

二.对指定方法进行校验

    不重写validate()方法,增加validateXxx方法,如validate Save,指只针对save方法进行校验。主要方法名首字母大写。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值