struts表单验证简单实现

来源:互联网 发布:下载360软件管家 编辑:程序博客网 时间:2024/05/21 17:05

struts表单验证简单实现

ActionForm

ActionForm这一个类中,有一个validate方法,用于提交表单后,自动封装Form后对于信息的验证。该方法返回类型是ActionErrors, ActionErrors有一方法put("name", new ActionMessage("errors.name.required"));用来保存错误信息,对于ActionMessage("errors.name.required"), 会从struts-config.xml中message-resources寻找对应的值,也可以使用ActionMessage("姓名不能为空",false),就不会从资源文件中查找

public class EmployeeForm extends ActionForm {/** *  */private static final long serialVersionUID = -1639028024718143236L;private String id;private String name;private String birthday;private String sex;private String address;private String[] love;private String education;@Overridepublic void reset(ActionMapping mapping, HttpServletRequest request) {// TODO Auto-generated method stubthis.id = null;this.name = null;this.birthday = null;this.sex = null;this.address = null;this.love = null;this.education = null;}//setr和get方法...@Overridepublic ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {// TODO Auto-generated method stubSystem.out.println("验证方法validate()走起....");ActionErrors errors = new ActionErrors();if(name == null || "".equals(name.trim())) {System.out.println("用户名为空");errors.add("name", new ActionMessage("errors.name.required"));}if(sex == null) errors.add("sex", new ActionMessage("errors.sex.required"));if(birthday == null || !birthday.matches("^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$")) errors.add("birthday", new ActionMessage("errors.birthday.date"));return errors;}}

资源文件

MessageResources_en_US.properties中存放错误信息
errors.header=<ul>errors.prefix=<li class="error">errors.suffix=</li>errors.footer=</ul>errors.sex.required=sex is required.errors.name.required=name is required.errors.birthday.date=birthday is not a date.

struts配置文件

在struts-config.xml文件中,默认validate="true",设置validate=“false”,不会进行validate方法验证,  并且当发现错误时,会跳转到input指定的页面,所以一定要设置input这一属性
        <action path="/EmployeeAction_Save" name="EmployeeForm" scope="request" type="com.struts.web.EmployeeAction" parameter="method" input="/Employee.jsp" validate="true">          <forward name="success" path="/PAGE/success_s.jsp"></forward>        </action>

jsp页面

在jsp中只需使用这一个标签,即可将所有错误显示出来    <html:errors/>
也可以使用 <html:errors property="key">将某一特定的错误输出,其中key代表就是errors.add("key",MessageActoin);中的第一个参数


最后展示一下当姓名性别生日都为空时的结果



0 0
原创粉丝点击