`
天边一朵雲
  • 浏览: 34923 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

(OTHER)Struts2后台验证

 
阅读更多
一. 手动输入完成校验:

1.普通的处理方式:只需要在action中重写validate()方法

2.一个action对应多个逻辑处理方法:指定校验摸个特定方法的方式:

重写validateXxxx()方法。Eg:如果,只校验login方法,则只需重写validateLogin().

二. 输入校验流程:

1. 类型转换器负责对字符串的请求参数执行类型转换。并将这些值设置成Action的属性值。

2. 转换过程中若出现异常,则将异常信息保存到ActionContext中,conversionError拦截器将其封装到fieldError中。

3. 通过反射调用validateXxx()方法。

4. 调用validate().

5. 如果未出现异常,则转入用户请求的处理方法,如果出现异常,则转入inout视图所指定的视图资源(所以,对于验证的方法,必须要在配置文件中为其指定input)。

三. 基于验证框架的输入校验

1. 编写校验配置文件:命名规则:action类名-validatin.xml. 
2. 一个action对应多个逻辑处理方法:指定校验摸个特定方法的方式: 
action类名-name属性名-validatin.xml.(name属性名:在strtus配置文件中的) 
3. 配置文件存放位置:放在与Action相同的文件夹内。 
4. 验证规则:先加载action类名-validatin.xml,
然后加载action类名-name属性名-validatin.xml文件。 
5. 校验器的配置风格:两种:字段校验器,非字段校验器。 
字段校验器配置格式: 
<field name="被校验的字段"> 
       <field-validator type="校验器名"> 
              <!--此处需要为不同校验器指定数量不等的校验规则--> 
              <param name="参数名">参数值</param> 
                  .................... 
              <!--校验失败后的提示信息,其中key指定国际化信息的key--> 
              <message key="I18Nkey">校验失败后的提示信息</message> 
              <!--校验失败后的提示信息:建议用getText("I18Nkey"),否则可能出现Freemarker template Error--> 
       </field-vallidator> 
       <!-- 如果校验字段满足多个规则,下面可以配置多个校验器--> 
</field> 
<!--非字段校验器配置格式:--> 
<validator type="校验器名"> 
          <param name="fieldName">需要被校验的字段</param> 
          <!--此处需要为不同校验器指定数量不等的校验规则-->         
<param name="参数名">参数值</param> 
          <!--校验失败后的提示信息,其中key指定国际化信息的key--> 
          <message key="I18Nkey">校验失败后的提示信息</message> 
          <!--校验失败后的提示信息:建议用getText("I18Nkey"),否则可能出现Freemarker template Error--> 
</validator> 
<!--非字段校验:先指定校验器:由谁来校验,来校验谁!--> 
<!--字段校验器:先指定校验的属性:我来校验谁,由谁来校验-->



1. 校验器:struts2提供了大量的内置校验器:你可以在xwork-core-2.1.6.jar的com.opensymphony.xwork2.validator.validators下找到如下配置文件:default.xml.里面列出了所有的内置校验器。

struts2表单验证里field-validator type值:
int 整数;
double 实数;
date 日期;
expression  两数的关系比较; 
email Email地址;
url
visitor
conversion 
regex 正则表达式验证;
required 是否为空;
requiredstring 必须字符;
stringlength 输入字符长度限制;
url web地址
visitor 访问
conversion 转换
<validators> 
<!—必填校验器 --> 
<validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/> 
<!—必填字符串校验器--> 
<validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/> 
<!-- 整数校验器 --> 
<validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/> 
<!-- --> 
<validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/> 
<validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/> 
<validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/> 
<!-- 日期校验器 --> 
<validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/> 
<!--  表达式校验器 --> 
<validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/> 
<!--  字段表达式校验器 --> 
<validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/> 
<!--  邮件校验器 --> 
<validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/> 
<!--  网址校验器 --> 
<validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/> 
<validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/> 
<!--  转换器校验器 --> 
<validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/> 
<!--  字符串长度校验器 --> 
<validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/> 
<!--  正则表达式校验器 --> 
<validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/> 
<validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/> 
</validators>

这些校验器已经可以满足大多数的验证需求,如果还需要特殊的要求,建议直接采用java代码搞定,除非你有很多地方都要用到,此时你可以自定义一个校验器。

四. 校验器的执行顺序

1. 所有非字段校验风格的校验器优先于字段校验风格的校验器;

2. 所有非字段校验风格的校验器中,排在前面的会先执行;

3. 所有字段校验风格的校验器,排在前面的会先执行;

五. 校验器的短路原则

1. 所有非字段检验器时最优先执行的,如果某个非字段校验器校验失败了,则该字段上的所有字段校验器都不会获得校验机会;

2. 非字段校验校验失败,不会阻止其他非字段校验执行;

3. 如果一个字段校验器校验失败后,则该字段下且排在该校验失败后的检验器之后的其他字段校验器不会获得校验机会;

4. 字段校验器永远不会阻止非字段校验器的执行!

六. 短路校验器

短路校验器:只需在或元素中添加short-circuit=”true”属性。

注:在struts2.1.6版本,已经支持客户端的短路校验。

七. 客户端的校验:

在中添加validate=”true”.

Struts2提供了客户端校验与服务端校验。这里只是做个简易的总结。

1.)服务端校验:

当程序流程进入到Action类,并经历了struts2的类型转换阶段后。接着进入struts2的输入校验阶段。

struts2的输入校验可自己编码进行校验,也可通过有规则命名的配置文件进行校验。

1.1)编码校验:

在Action类里重写父类的validate()方法即可。

public void validate(){
    if(null == username || "".equals(username)){
        this.addFieldError("username","username should not be empty !");
    }else if(username.length() < 6 || username.length() > 12){
        this.addFieldError("username","username should be between 6 and 12 !");
    }

    if(null == password || "".equals(password )){    
        this.addFieldError("password ","password should not be empty !");
    }else if(password .length() < 6 || password .length() > 12){
        this.addFieldError("password ","password should be between 6 and 12 !");   
    }
}

在上面的validate方法中,一旦发现校验失败,就把失败提示通过addFieldError方法添加到系统的fieldError中。校验完毕后,若系统的fieldError不为空,则自动转到input视图对应的JSP页面中输出错误提示,这与类型转换失败后的处理是完全一样的。

为了在input视图中对应的JSP页面输出错误提示,应该在该页面中增加如下代码:

这里不能忽略另外种情况:Struts2的Action类里可以包含多个处理逻辑,不同的处理逻辑对应不同的方法。即Struts2的Action类里定义了几个类似于execute的方法,只是方法名不同。而重写validate方法无法知道需要校验的是哪个处理逻辑。实际上重写validate方法会校验所有的处理逻辑。

为了校验指定处理逻辑,需提供一个validateXxx()方法,其中xxx为Action对应的处理逻辑方法。

例如Action类里有个login()逻辑方法,那么对应的校验方法validateLogin()方法。

但之后还是会调用validate()进行校验,因此此时validate()没必要写了,或者让validate()进行公共字段的校验。

1.2)配置文件校验

只需为Action指定一个校验文件即可。在Action类所在的com.test.action包下建立LoginAction-validation.xml校验文件(格式:Action类名-validation.xml).

LoginAction-validation.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
 "-//OpenSymphony Group//XWork Validator 1.0.2//EN" 
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>

   <field name="username">
     <field-validator type="requiredstring">
       <param name="trim">true</param>
       <message>username should not be empty !</message>
     </field-validator>
   
     <field-validator type="stringlength">
       <param name="minLength">6</param>
       <param name="maxLength">12</param>
       <message>username should be between
 ${minLength} and ${maxLength}!</message>
     </field-validator>
   </field>
   
   <field name="password">
     <field-validator type="requiredstring">
       <param name="trim">true</param>
       <message>password should not be empty !</message>
     </field-validator>
   
     <field-validator type="stringlength">
       <param name="minLength">6</param>
       <param name="maxLength">12</param>
       <message>password should be between
 ${minLength} and ${maxLength}!</message>
     </field-validator>
   </field>
       
</validators>


每个元素指定一个Action属性必须遵守的规则,该元素name属性指定了被校验的字段;如果该属性满足多个规则,则在该下增多个。

每个指定一个校验规则,该元素的type属性指定校验器名称该元素可以包含多个子元素,用户指定该校验器的参数;除外,每个元素都有一个必须的元素,用户确定校验失败后的提示信息。

例子中只采用了"必填字符串校验器"和"字符串长度校验器"2个校验规则。

struts2貌似共提供了13个校验器:
required:必填校验器
requiredstring:必填字符串校验器
int:整数校验器
double:双精度浮点数校验器
date:日期校验器
expression:表达式校验器
fieldexpression:字段表达式校验器
email:电子邮件校验器
url:网址校验器
visitor:Visitor校验器
conversion:转换校验器
stringlength:字符串长度校验器
regex:正则表达式校验器

用法大部分雷同,用到的时候可自己google搜索。

配置文件校验肯定不输给编码校验的,自然也提供了对应于具体业务逻辑的校验规则文件的格式:

例:

<!-- 配置一个名为user的Action,对应的逻辑方法为UserAction的login方法-->

<action name="login" class="com.test.action.UserAction" method="login">
    <result name="input">/login.jsp</result>
    <result name="success">/index.jsp</result>
</action>

则此逻辑方法对应的校验规则文件为:
UserAction-login-validation.xml

与编码校验一样,校验错误信息会添加到系统的fieldError中,校验完毕后若FieldError不为空。则进入到input视图对应的JSP。在处输出错误提示。

提醒:没记错的话。与编码校验不同的是校验顺序,配置文件校验方式下,

先UserAction-validation.xml,再UserAction-login-validation.xml,

因此若是只针login()逻辑进行输入校验的话,那UserAction-validation.xml没必要写了,或让其进行公共字段的校验

2)客户端校验

增加客户端校验非常简单,将输入页面的表单元素改为使用struts2标签来生成表单,并且为该表单增加validate="true"属性即可。

来源:赛迪网 http://news.ccidnet.com/art/32855/20100713/2113783_1.html

分享到:
评论

相关推荐

    struts2官方开发文档

    For other community-supported Struts resources, visit the Struts 2 Wiki. The contents of the Struts 2 documentation wiki (what you're reading now) are distributed with each release, but maintained via...

    struts-spring-other-lib 等jar包

    struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-other-lib 等jar包struts-spring-...

    Struts2.3.16.3 chm帮助文档

    For other community-supported Struts resources, visit the Struts 2 Wiki. The contents of the Struts 2 documentation wiki (what you're reading now) are distributed with each release, but maintained via...

    Struts 2 Form Tags

    In this tutorial we'll explore some of the other Struts 2 form controls. In our previous tutorials that explained how to use Struts 2 forms (Processing Forms, Form Validation, and Message Resource ...

    struts2 in action

    To be honest, I can no longer recall why I chose Struts 2. I know that I also consid- ered using Spring’s MVC framework, but something made me go with Struts 2. I prob- ably chose Struts 2 because I...

    Practical Apache Struts2 Web 2.0 Projects

    Integrate and use Struts 2 with other frameworks such as Spring to form a broader enterprise Java application stack. Who is this book for? Developers who want a hands–on practical book ...

    Struts2上传所需jar包

    2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable...

    struts1.3.9.zip

    struts1.3.9 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the ...

    struts2.3.12GA(HTML版)

    Last Published: 2013-03-16 Struts 1 | Struts 2 | Apache APACHE STRUTS Welcome Releases Announcements License Kickstart FAQ Website Stats Thanks! Sponsorship DOCUMENTATION Key Technologies Struts ...

    Programming_Jakarta_Struts(英文第二版)

    Other solutions do not—those that fail to serve the needs of users and add value usually fall by the wayside. &lt;br&gt;Through this evolutionary process, the Jakarta Struts framework (created by Craig...

    struts spring lib

    aspectjrt.jar aspectjweaver.jar borlandxml.jar cglib-nodep-2.1_3.jar classes12.jar common-annotations.jar ...struts-spring-other-lib.rar struts.jar unittest.jar xercesImpl.jar xmlParserAPIs.jar

    other 和another的区别

    2)others(=other+复数名词) 代词,泛指“部分”含义,用于已知的一些人或物中,除去某些后余下的人或物中的一部分。在句中可作主语、宾语。例如: The students of Class Four are cleaning the classroom. Some ...

    Options, Futures and Other Derivatives.part2

    Options, Futures and Other Derivatives.part2

    hibernate3.1和struts1.2不兼容问题

    hibernate3.1和struts1.2构建网站时出现 如下错误提示:“java.lang.SecurityException: class "org.apache.commons.collections.SequencedHashMap"'s signer information does not match signer information of ...

    chunyou_other_part2

    chunyou_other_part2 chunyou_other_part2 chunyou_other_part2

    Struts Taglibs经典开发指南

    This taglib contains tags used to create struts input forms, as well as other tags generally useful in the creation of HTML-based user interfaces.

    struts 标签 logic:iterate使用 logic:iterate

    我就是靠这个文档实现logic:iterate的循环的 struts 标签 logic:iterate使用 logic:iterate &lt;br&gt;第一页 是struts官方的说明, 第二页 是个例子 第三页 是我实现的arrayList放入标签的方法。 这是页面...

    Other_the_other_another_others练习题.pdf

    Other_the_other_another_others练习题.pdf

    struts2.0教程(pdf)

    Apache Struts is one of the most ...few other open source frameworks have managed to have the success, popularity, market dominance, and ability to change the way developers think as Struts has.

    Other_demo2.py

    Other_demo2.py

Global site tag (gtag.js) - Google Analytics