ITeye博客

Struts验证框架与一些技巧

skin_deng · 2010-06-15 08:33 · Struts · 企业架构 · Markdown

还是通过一些步骤例子说明 首先建立Struts工程的时候要启动验证框架。 它称为Validator验证框架

主要依赖与两个.jar文件 Jakarta-oro.jar Commons-validator.jar

这个是在struts-config.xml文件中如下加入配置之后即代表该工程已经使用验证框架的插件了


<plug-in className="org.apache.struts.validator.ValidatorPlugIn">    
        <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>    
</plug-in>  

完成好了之后以注册的例子说明它的主要使用方法 1.建立一个注册的页面;包含用户名: 密码: 年龄: 邮箱:都不能为空。密码长度必须大于或等于8位,邮箱格式验证等 显示方式一:使用错误消息显示在相应的控件后面。 2.建立注册页相对应的表单Bean(ActionForm),重点在这里,因为要使用验证框架的话该表单类需要修改 1)修改该类的继承


import org.apache.struts.validator.ValidatorForm;// 导入要继承的类    
public class 表单类 extends ValidatorForm //修改继承类  

  1. //修改该类且不包含validate()方法. 3、在validation.xml 中配置验证规则 这个验证规则依赖与validator-rules.xml此文件已经配置好的验证类 大概介绍几种规则吧{}中的为参数 errors.required={0} is required. 必须的,或者不能为空的 errors.minlength={0} can not be less than {1} characters. {某某}不能小于{多少}位 errors.maxlength={0} can not be greater than {1} characters.{ 某某}不能大于{多少}位 errors.range={0} is not in the range {1} through {2}.{0}是不能在{1}与{2}之间

<form-validation>   <!--以下是配置一些常用的验证规则 -->  
  <formset>    
<form name="regActionForm">     
<!--表单名,为验证哪个表单而配置,这里的name指定struts中form-bean的别名 -->  
    <field property="username" depends="required">    
      <arg0 key="tip.username"/>    
    </field>         arg0指要为该规则传入的第一个参数    
<!--property为表单中的属性,depends为要验证的规则key为消息资料文件中的配置键 -->  
<!-- 验证密码最小长度不小于8位 要一个控件属性验证两个规则的话真正以逗号分开, -->    
  
<field property="userpass" depends="required,minlength">    
      <arg0 key="tip.userpass"/>    
      <arg1 key="${var:minlength}" name="minlength" resource="false"/>    
      <var>    
        <var-name>minlength</var-name>    
        <var-value>8</var-value>    
      </var>    
    </field>    
    
    <!--绿色的为变量名,好像定义也有规则,必须是那样而resource 则是配置是否从资源文件中查找key -->  
       
  
<field property="email" depends="required,email">    
      <arg0 key="tip.email"/>    
    </field>    
    
<!-- 验证年龄在一定范围之内 -->  
    <field property="age" depends="required,intRange">    
      <arg0 key="tip.age"/>    
      <arg1 key="${var:min}" name="intRange" resource="false"/>    
      <arg2 key="${var:max}" name="intRange" resource="false"/>    
       <var>    
         <var-name>min</var-name>    
         <var-value>1</var-value>    
       </var>    
       <var>    
         <var-name>max</var-name>    
         <var-value>100</var-value>    
       </var>    
    </field>    
    </form>    
  </formset>    
</form-validation>   

4、编写消息资源文件

验证规则的配置文件中所用key的名字为该资源文件所配置


# errors.required={0}不能为空.    
# tip.username=用户名    
# tip.userpass=密码    
# errors.minlength={0}不能少于{1}个字符.    
# errors.email={0} 格式不合法.    
# tip.email=邮箱    
# tip.age=年龄    
# errors.range={0} 必须在 {1} - {2} 之间.    
  
errors.required={0}\u4e0d\u80fd\u4e3a\u7a7a.    
tip.username=\u7528\u6237\u540d    
tip.userpass=\u5bc6\u7801    
errors.minlength={0}\u4e0d\u80fd\u5c11\u4e8e{1}\u4e2a\u5b57\u7b26.    
errors.email={0} \u683c\u5f0f\u4e0d\u5408\u6cd5.    
tip.email=\u90ae\u7bb1    
tip.age=\u5e74\u9f84    
errors.range={0} \u5fc5\u987b\u5728 {1} - {2} \u4e4b\u95f4.   

5.在struts-config.xml中配置Action验证失败跳转页面,属性为input指向的地方

二、手工验证; 1、用户名、密码不能为空; 2、密码长度不能小于8位;

(1)验证代码写在哪儿? ActionForm的validate()方法中,如果该方法返回的ActionErrors中没有包含错误消息,认为验证通过。

(2)错误集合存在哪儿? 由 RequestProcessor 将错误集合存储在 Request 中,键名为 Globas.ERROR_KEY;

(3)如何显示错误消息?


<html:errors/> <!--显示所有消息 -->  
<html:errors property="xx"/> <!--显示指定的消息-->  

三、生成JavaScript (1)ActionForm继承 org.apache.struts.validator.ValidatorForm; (2)ActionForm中无 validate() 方法; (3)表单JSP页中加: <html:form .... onsubmit="return validateRegForm(this);">颜色字体一致,首字母大写 <html:javascript formName="regForm"/> (4)在validation.xml中配置验证规则;

另外再说一个不怎么常用的标签,它的作用一般就是方便表单Bean对象的重复代码


<%@ taglib uri="/WEB-INF/struts-nested.tld" prefix="nested" %>    
<h1>用户注册</h1>    
<html:form action="reg.do" method="post">    
  <nested:nest property="user">      
    用户名:<nested:text property="username"/><br/>    
    密码:<nested:text property="userpass"/><br/>    
  </nested:nest>    
  <html:submit value="提交"/>    
</html:form>   

要使用该配置,在ActionForm中要实例化一个user对象才可以通过以上配置使用对象中username的属性


<hr>    
<h1>用户注册</h1>    
<html:form action="reg.do" method="post">    
    用户名:<html:text property="user.username"/><br/>    
    密码:<html:text property="user.userpass"/><br/>    
  <html:submit value="提交"/>    
</html:form>   

上面的代码也可以实现刚才的功能,但是在验证框架中就不能那么使用了


<tiles:insert page="header.jsp" flush="true"/><!--标头内容 -->  
</html:form>   

作用与嵌套网页,可以定制好一个模板,然后在模板中使用相应的可编辑内容


<h1>t1.jsp</h1>    
111111111111111    
<hr>    
<!--page表示所要插入的网页,flush是否及时更新 -->  
<tiles:insert page="footer.jsp" flush="true"/><!--末尾内容 -->  

第二种情况是以一个定制了的模板生成个新的网页


<tiles:insert attribute="header"/>    
<tiles:insert attribute="footer"/>    
  
<tiles:insert page="template1.jsp" flush="true">   <!--已经存在一个template1.jsp模板 -->  
<tiles:put name="header" value="header.jsp"/>  <!--往属性header设置嵌入页面 -->  
<tiles:put name="footer" value="footer.jsp"/>    <!--往属性footer设置嵌入页面 -->  
</tiles:insert>   

(1)防止重复提交; Action 原理是通过在请求里面加入一些身份标记,在请求的时候判断是否事先存放的标记,如果不是则是第二次非正常提交


this.saveToken(request);        //在第一次点击请求的时候存入然后存转发到另一个JSP页面    
//判断令牌是否有效;    
if(! this.isTokenValid(request) ){     //如果是刚才的页面转发过来的话则它返回真    
saveToken(request);    
return ( new ActionForward(mapping.getInput()) );     
//跳转到Action配置的input中的页面    
}    
//最后正常执行完业务逻辑就把先前存的Token删除    
request.removeAttribute(mapping.getAttribute());    
this.resetToken(request);   

(2)动态ActionForm(对应的JAVA类是动态产生的,JAVA类中的属性在struts-config.xml文件中动态配置) 1.配置Struts-config.xml中的 ,在其中声明 表单中要包含的字段元素;

例如页面上有以下一个表单 ,分别有属性username userage


<form action="dynaReg.do" method="post">    
username:<input size=10 name="username"><br>    
userage:<input size=10 name="userage"><br>    
<input type="submit" value=" OK ">    
</form>   

那么对应这个表单就要在Struts-config.xml中配置一个与其对应的form-bean


<form-bean name="dynaRegForm" dynamic="true" type="org.apache.struts.action.DynaActionForm"> <!--指定该bean为动态的,并类型是该类    
如果使用了动态FORMBEAN也想用验证框架的话这里的TYPE就要指定DynaValidatorActionForm -->  
        <form-property name="username" type="java.lang.String"/>    
        <form-property name="userage" type="java.lang.Integer" initial="0"/>    
</form-bean>   


2.配置Struts-config.xml中的 ,将动态ActionForm 与某个Action结合起来; 只要name属性名称一致就可以了 在Action中的业务方法有些改动,因为它自动生成表单bean,所以取值的时候要像这样取,get中填写xml配置中的属性名字,把form强转换成DynaActionForm类对象,使用.get方法,返回Object,所以相应的再强转成想要的类型 String username=(String)((DynaActionForm)form).get("username"); Integer userage=(Integer)((DynaActionForm)form).get("userage"); 3.客户使用表单,表单中名称与中声明的相同;

最后在使用完表单bean之后要删除掉刚才生成的bean;方法如下 request.removeAttribute(mapping.getAttribute());//删除FormBean

(3)DispatchAction类,可以在一个Action中编写多个业务方法; 1、编写Action,要继承DispatchAction,且无execute()方法; 2、在Action类中提供多个业务方法; 3、在表单/超链接中生成请求时,用URL: xxxxx.do?method=XX 4、使用该类,可以节省Action的个数;

测试DispatchAction类(一个Action处理多种业务): 加math.do?method=add 减math.do?method=dec 乘math.do?method=mul

在Action类中要写入相应的方法。


public ActionForward add(ActionMapping mapping,    
                            ActionForm form,    
                            HttpServletRequest request,    
                            HttpServletResponse response)    
    throws Exception {    
    System.out.println("add....");    
    request.setAttribute( "mathresult","add...." );    
    return mapping.findForward( "success" );    
    }   


其他几个以此类推。。。。。。。。。。。。

(4)一个表单实现多种业务(计算器)----LookupDispatchAction; LookupDispatchAction(一个表单对应多个处理方法):

1、编写Action,继承LookupDispatchAction类; 2、重写LookupDispatchAction类的getKeyMethodMap(),在该方法内对提交按钮文字“键名”和“业务方法名”进行映射;


protected Map getKeyMethodMap(){    
Map map=new HashMap();    
map.put("页面显示的按钮","本类中的业务方法名");    
map.put("button.add ","add");    
return map;    
}   

3、编写业务方法;


//add    
    public ActionForward add(ActionMapping mapping,    
                                 ActionForm form,    
                                 HttpServletRequest request,    
                                 HttpServletResponse response)    
    throws Exception    
    {    
  
        int num1 = ((Math2Form) form).getNum1();    
        int num2 = ((Math2Form) form).getNum2();    
request.setAttribute( "math2Result", ""+(num1+num2) );    
        request.removeAttribute(mapping.getAttribute());    
        return (mapping.findForward("success"));    
    }   


4、表单中的提交按钮中,显示文字时使用


<bean:message key="xxx"/> 

5、使用该类,可以出现许多避免重复性表单;(如下为前台表单显示的内容)


<html:submit property="action">    
<bean:message key="button.add"/>    
</html:submit>   

(5)ForwardAction


<action       
path = "/jsp1"    
type = "org.apache.struts.actions.ForwardAction"    
parameter ="/jsp1.jsp"    
/>    
  
<action       
path = "/jsp1"    
forward="/jsp1.jsp"    
/>   


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。