复习struts2之对action中所有方法进行输入校验

来源:互联网 发布:全国各乡镇人口数据 编辑:程序博客网 时间:2024/05/16 14:57
在struts2中,我们可以实现对action的所有方法进行校验或者对action的指定方法进行校验。 对于输入校验struts2提供了两种实现方法: 1. 采用手工编写代码实现。 2. 基于XML配置方式实现。方法一实例:index.jsp<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>    <%@ taglib uri="/struts-tags" prefix="s" %>    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>输入校验</title></head><body><!-- 用于显示错误信息 --><s:fielderror/><form action="${pageContext.request.contextPath }/test/helloword.do" method="post">用户名:<input type="text" name="username"/><br/>手机号:<input type="text" name="mobile"/><br/><input type="submit" value="提交"/></form></body></html>struts.xml文件<action name="helloword" class="cn.itcast.action.HelloWordAction" method="save"><result name="input">/index.jsp</result><result name="success">/WEB-INF/page/message.jsp</result></action>HelloWord.java定义两个属性private String username;private String mobile;在此省略以上两个属性的set和get方法public String update(){ActionContext.getContext().put("message", "更新成功");return "success";}public String save(){ActionContext.getContext().put("message", "保存成功");return "success";}@Overridepublic void validate() {//会对action中的所有方法校验if(this.username==null || "".equals(username.trim())){//添加错误信息this.addFieldError("username", "用户名不能为空");}if(this.mobile==null || "".equals(mobile.trim())){this.addFieldError("mobile", "手机号不能为空");}else{if(!Pattern.compile("^1[358]\\d{9}$").matcher(mobile).matches()){this.addFieldError("mobile", "手机号格式不正确");}}}message.jsp${message}