Samuel Learning

  • 联系
  •  
  • 管理

文章分类(203)

  • 01 ASP/HTML(6)
  • 02 Script/CSS(16)
  • 03 C/C++
  • 04 XML(4)
  • 05 微软编程(26)
  • 06 J2EE(60)
  • 09 Linux(14)
  • 10 Database(27)
  • 11 报表打印
  • 12 打包安装(1)
  • 13 模式重构(2)
  • 14 系统架构
  • 15 敏捷开发(11)
  • 16 案例分析(30)
  • 17 Workflow(1)
  • 18 配置管理(1)
  • 19 项目管理
  • 20 英语(4)

新闻分类(52)

  • CXF学习
  • Hibernate学习(1)
  • iBatis学习(16)
  • Struts1学习(1)
  • Struts2学习(34)

.NET资源

  • adxmenu
  • C# Open Source
  • DNN Directory
  • M2Land
  • Windows Form FAQ
  • 中国DNN
  • 中国DNN联盟

Ajax

  • DoJo
  • GWT
  • JQuery
  • jquery autocomplete
  • jquery flexgrid
  • JQuery Form
  • jquery masked input
  • JQuery UI
  • jquery validation
  • Jquery 图表
  • jquery报表
  • jquery插件集合
  • Qooxdoo
  • Tibco GI
  • YUI
  • YUI-EXT
  • ZeroKode

Java开源

  • ABLE
  • Agile Tao
  • Ajax4JSF
  • Alfresco
  • AppFuse
  • Compiere
  • Equinox
  • Findbugs
  • Geronimo
  • Grails
  • Harmony
  • Hibernate论坛
  • JAG
  • Java开源大全
  • Java视线论坛
  • jBPM工作流
  • JSFTutorials
  • Nereide ERP
  • Ofbiz ERP
  • Opentaps ERP
  • operamasks
  • Petstore
  • Prototype.js
  • RIFE
  • Runa
  • SpringSide
  • Struts Menu
  • Sun Glassfish
  • Trails
  • YUI4JSF
  • 满江红

Mobile

  • Sencha

WEB资源

  • DHTML中心
  • DHTML参考手册
  • DHTML文档
  • EclipsePlugin
  • Firebug
  • GRO Clinux
  • jMaki
  • JSTL文档
  • LoadIcon
  • Openlaszlo
  • Struts Menu 展示
  • Web Test Tools
  • WebCtrs
  • Webdeveloper
  • 中国RIA开发者论坛

Workflow

  • E-Workflow
  • JBPM
  • OpenWFE
  • OSWorkflow
  • WFMC
  • Workflow Research

其他连接

  • confach
  • CPP
  • ejay
  • Giovanni
  • 丹佛
  • 交大e-learning
  • 交大研究生院
  • 可恶的猫
  • 天天@blog
  • 我的相册
  • 阿飞

大牛人

  • 32篇JBPM
  • David.Turing
  • HongSoft@业务集成
  • Joel
  • Koen Aers
  • Martinfowler
  • Raible Matt
  • Raible Wiki
  • Scott W.Ambler
  • Tom Baeyens
  • Uncle Bob
  • 一个世界在等待
  • 子在川上曰
  • 小布老师
  • 小明
  • 差沙
  • 徐昊
  • 江南白衣
  • 汪博士
  • 汪小金
  • 银狐999

开源软件

  • 2Bizbox ERP
  • CompiereCRM&ERP
  • EGW
  • Vtiger CRM
  • webERP

敏捷

  • Canoo
  • Cruisecontrol
  • DBUnit
  • EL4Ant
  • Extreme Programming
  • Fit
  • Fitnesse
  • JFrog
  • Liquibase
  • Maven
  • MockObjects
  • Selenium
  • Squish
  • xpairtise
  • XPlanner
  • XProgramming
  • 敏捷联盟

数据库

  • Oracle 中国
  • Oracle-ERP
  • Oracle在线社区

未归类

  • Aquarius Orm Studio
  • mambo建站系统
  • Oracle产品下载
  • 远程同步管理工具Capivara

经典框架

  • Apache Shale
  • formdef-struts
  • FreeMarker 主页
  • JBoss Seam
  • JSF 中心
  • JSF 入门应用
  • JSF中国
  • MyFaces官方
  • Spring 社区
  • Spring专业网站
  • Spring中文论坛
  • Spring参考手册
  • Spring官方网站
  • strecks-struts
  • Struts1
  • Struts2
  • Struts-layout
  • StrutsWiKi
  • Tapestry WIKI
  • Tapestry 官方
  • Tapestry4开发指南
  • Tapestry中文文档
  • Webwork2文档
  • Wicket

网络教程

  • Laliluna
  • RoseIndia
  • Sang Shin
  • Visualbuilder

著名站点

  • Buildix
  • Dev2Dev
  • IBM dev中国
  • InfoQ
  • ITPub
  • Java Eye
  • Java Research
  • JavaRead
  • JavaWorldTW
  • Matrix
  • PHP100
  • PHPX
  • SpringSideWiKi
  • TheServerSide
  • TWPHP
  • 中国工作流论坛

项目管理

  • 管理人网

最新评论

View Post

Struts2 Validation[笔记]

Struts Action 2 relies on a validation framework provided by [XWork] to enable the application of input validation rules to your Actions before they are executed. This section only provides the bare minimum to get you started and focuses on our extension of the XWork validators to support client-side validation.

Struts Action 2 依赖于一个XWork提供的validation框架,它能够在执行Action之前,遵循一些输入验证规则。本节进京提供最小的能够让你开始和关注于对XWork validator扩展来支持客户端的验证。

There is also an option for Client Side (Javascript and/or AJAX) based validation, please see Client Side Validation for more information.

Using Annotations

Annotations can be used as an alternative to XML for validation.

Annotations 方式的验证是一个相对于XML更好的选择。

Examples

  1. Basic Validation
  2. Client Validation
  3. AJAX Validation
  4. Using Field Validators
  5. Using Non Field Validators
  6. Using Visitor Field Validator

Bundled Validators

Note

When using a Field Validator, Field Validator Syntax is ALWAYS preferable than using the Plain Validator Syntax as it facilitates grouping of field-validators according to fields. This is very handy especially if a field needs to have many field-validators which is almost always the case. Examples: validatortypes

  1. required validator
  2. requiredstring validator
  3. int validator
  4. date validator
  5. expression validator
  6. fieldexpression validator
  7. email validator
  8. url validator
  9. visitor validator
  10. conversion validator
  11. stringlength validator
  12. regex validator

Registering Validators

Validation rules are handled by validators, which must be registered with the ValidatorFactory (using the registerValidator method). The simplest way to do so is to add a file name validators.xml in the root of the classpath (/WEB-INF/classes) that declares all the validators you intend to use.

This list declares all the validators that comes with the framework.

<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="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"/>
</validators>
Note

validators.xml if being defined should be available in the classpath. However this is not necessary, if no custom validator is needed. Predefined sets of validators will automatically be picked up when defined in com/opensymphony/xwork2/validator/validators/default.xml packaged in in the xwork jar file. See ValidatorFactory static block for details.

Warning

If custom validator is being defined and a validators.xml is created and place in the classpath, do remember to copy all the other pre-defined validators that is needed into the validators.xml as if not they will not be registered. Once a validators.xml is detected in the classpath, the default one (com/opensymphony/xwork2/validator/validators/default.xml) will not be loaded. It is only loaded when a custom validators.xml cannot be found in the classpath. Be careful.

自己的validator.xml和default.xml是二选一。

Turning on Validation

The default validationWorkflowStack already includes this.
All that is required to enable validation for an Action is to put the ValidationInterceptor in the interceptor refs of the action (see xwork.xml) like so:

<interceptor name="validator" class="com.opensymphony.xwork2.validator.ValidationInterceptor"/>

Note: The default validationWorkflowStack already includes this.

You can turn off validation for a specific method by using the @SkipValidation annotation above your action method.

你可以关闭对某个方法的验证,使用@SkipValidation annotation在你的action 方法上面。

Validator Scopes

Field validators, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation whereever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.

Non-field validators only add action level messages. Non-field validators are mostly domain specific and therefore often custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.

上面提到两种Validator, Field Validator和Non-field validator.

Notes

Non-field validators takes precedence over field validators regardless of the order they are defined in *-validation.xml. If a non-field validator is short-circuited, it will causes its non-field validator to not being executed. See validation framework documentation for more info.

Defining Validation Rules

Validation rules can be specified:

  1. Per Action class: in a file named ActionName-validation.xml
  2. Per Action alias: in a file named ActionName-alias-validation.xml
  3. Inheritance hierarchy and interfaces implemented by Action class: XWork searches up the inheritance tree of the action to find default validations for parent classes of the Action and interfaces implemented
Here is an example for SimpleAction-validation.xml:
<!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="bar">
<field-validator type="required">
<message>You must enter a value for bar.</message>
</field-validator>
<field-validator type="int">
<param name="min">6</param>
<param name="max">10</param>
<message>bar must be between ${min} and ${max}, current value is ${bar}.</message>
</field-validator>
</field>
<field name="bar2">
<field-validator type="regex">
<param name="regex">[0-9],[0-9]</param>
<message>The value of bar2 must be in the format "x, y", where x and y are between 0 and 9</message>
</field-validator>
</field>
<field name="date">
<field-validator type="date">
<param name="min">12/22/2002</param>
<param name="max">12/25/2002</param>
<message>The date must be between 12-22-2002 and 12-25-2002.</message>
</field-validator>
</field>
<field name="foo">
<field-validator type="int">
<param name="min">0</param>
<param name="max">100</param>
<message key="foo.range">Could not find foo.range!</message>
</field-validator>
</field>
<validator type="expression">
<param name="expression">foo lt bar </param>
<message>Foo must be greater than Bar. Foo = ${foo}, Bar = ${bar}.</message>
</validator>
</validators>

Here we can see the configuration of validators for the SimpleAction class. Validators (and field-validators) must have a type attribute, which refers to a name of an Validator registered with the ValidatorFactory as above. Validator elements may also have <param> elements with name and value attributes to set arbitrary parameters into the Validator instance. See below for discussion of the message element.

Each Validator or Field-Validator element must define one message element inside the validator element body. The message element has 1 attributes, key which is not required. The body of the message tag is taken as the default message which should be added to the Action if the validator fails.Key gives a message key to look up in the Action's ResourceBundles using getText() from LocaleAware if the Action implements that interface (as ActionSupport does). This provides for Localized messages based on the Locale of the user making the request (or whatever Locale you've set into the LocaleAware Action). After either retrieving the message from the ResourceBundle using the Key value, or using the Default message, the current Validator is pushed onto the ValueStack, then the message is parsed for \${...} sections which are replaced with the evaluated value of the string between the \${ and }. This allows you to parameterize your messages with values from the Validator, the Action, or both.

If the validator fails, the validator is pushed onto the ValueStack and the message� either the default or the locale-specific one if the key attribute is defined (and such a message exists)� is parsed for ${...} sections which are replaced with the evaluated value of the string between the ${ and }. This allows you to parameterize your messages with values from the validator, the Action, or both.

NOTE:Since validation rules are in an XML file, you must make sure you escape special characters. For example, notice that in the expression validator rule above we use ">" instead of ">". Consult a resource on XML for the full list of characters that must be escaped. The most commonly used characters that must be escaped are: & (use &), > (user >), and < (use <).

Here is an example of a parameterized message:

This will pull the min and max parameters from the IntRangeFieldValidator and the value of bar from the Action.

bar must be between ${min} and ${max}, current value is ${bar}.

Validation rules can be specified:

  1. Per Action class: in a file named ActionName-validation.xml
  2. Per Action alias: in a file named ActionName-alias-validation.xml
  3. Inheritance hierarchy and interfaces implemented by Action class: XWork searches up the inheritance tree of the action to find default validations for parent classes of the Action and interfaces implemented
Here is an example for SimpleAction-validation.xml:

Validator Flavour

The validators supplied by the Xwork distribution (and any validators you might write yourself) come in two different flavors:

  1. Plain Validators / Non-Field validators
  2. FieldValidators

Plain Validators (such as the ExpressionValidator) perform validation checks that are not inherently tied to a single specified field. When you declare a plain Validator in your -validation.xml file you do not associate a fieldname attribute with it. (You should avoid using plain Validators within the syntax described below.)

FieldValidators (such as the EmailValidator) are designed to perform validation checks on a single field. They require that you specify a fieldname attribute in your -validation.xml file. There are two different (but equivalent) XML syntaxes you can use to declare FieldValidators (see " vs. syntax" below).

There are two places where the differences between the two validator flavors are important to keep in mind:

  1. when choosing the xml syntax used for declaring a validator (either or )
  2. when using the short-circuit capability

NOTE:Note that you do not declare what "flavor" of validator you are using in your -validation.xml file, you just declare the name of the validator to use and WebWork will know whether it's a "plain Validator" or a "FieldValidator" by looking at the validation class that the validator's programmer chose to implement.

Non-Field Validator Vs Field-Validator

There are two ways you can define validators in your -validation.xml file:

  1. <validator>
  2. <field-validator>

Keep the following in mind when using either syntax:

Non-Field-Validator The <validator> element allows you to declare both types of validators (either a plain Validator a field-specific FieldValidator).

<!-- Declaring a plain Validator using the <validator> syntax: -->

<validator type="expression>
<param name="expression">foo gt bar</param>
<message>foo must be great than bar.</message>
</validator>
<!-- Declaring a field validator using the <validator> syntax; -->

<validator type="required">
<param name="fieldName">bar</param>
<message>You must enter a value for bar.</message>
</validator>

field-validator The <field-validator> elements are basically the same as the <validator> elements except that they inherit the fieldName attribute from the enclosing <field> element. FieldValidators defined within a <field-validator> element will have their fieldName automatically filled with the value of the parent <field> element's fieldName attribute. The reason for this structure is to conveniently group the validators for a particular field under one element, otherwise the fieldName attribute would have to be repeated, over and over, for each individual <validator>.

HINT: It is always better to defined field-validator inside a <field> tag instead of using a <validator> tag and supplying fieldName as its param as the xml code itself is clearer (grouping of field is clearer)

NOTE: Note that you should only use FieldValidators (not plain Validators) within a block. A plain Validator inside a <field> will not be allowed and would generate error when parsing the xml, as it is not allowed in the defined dtd (xwork-validator-1.0.2.dtd)

Declaring a FieldValidator using the <field-validator> syntax:

<field name="email_address">
<field-validator type="required">
<message>You cannot leave the email address field empty.</message>
</field-validator>
<field-validator type="email">
<message>The email address you entered is not valid.</message>
</field-validator>
</field>

The choice is yours. It's perfectly legal to only use elements without the elements and set the fieldName attribute for each of them. The following are effectively equal:

有多个选择未必是好事情:)

<field name="email_address">
<field-validator type="required">
<message>You cannot leave the email address field empty.</message>
</field-validator>
<field-validator type="email">
<message>The email address you entered is not valid.</message>
</field-validator>
</field>


<validator type="required">
<param name="fieldName">email_address</param>
<message>You cannot leave the email address field empty.</message>
</validator>
<validator type="email">
<param name="fieldName">email_address</param>
<message>The email address you entered is not valid.</message>
</validator>

Short-Circuiting Validator

Beginning with XWork 1.0.1 (bundled with WebWork 2.1), it is possible to short-circuit a stack of validators. Here is another sample config file containing validation rules from the Xwork test cases: Notice that some of the <field-validator> and <validator> elements have the short-circuit attribute set to true.

<!DOCTYPE validators PUBLIC 
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<!-- Field Validators for email field -->
<field name="email">
<field-validator type="required" short-circuit="true">
<message>You must enter a value for email.</message>
</field-validator>
<field-validator type="email" short-circuit="true">
<message>Not a valid e-mail.</message>
</field-validator>
</field>
<!-- Field Validators for email2 field -->
<field name="email2">
<field-validator type="required">
<message>You must enter a value for email2.</message>
</field-validator>
<field-validator type="email">
<message>Not a valid e-mail2.</message>
</field-validator>
</field>
<!-- Plain Validator 1 -->
<validator type="expression">
<param name="expression">email.equals(email2)</param>
<message>Email not the same as email2</message>
</validator>
<!-- Plain Validator 2 -->
<validator type="expression" short-circuit="true">
<param name="expression">email.startsWith('mark')</param>
<message>Email does not start with mark</message>
</validator>
</validators>

short-circuiting and Validator flavors

Plain validator takes precedence over field-validator. They get validated first in the order they are defined and then the field-validator in the order they are defined. Failure of a particular validator marked as short-circuit will prevent the evaluation of subsequent validators and an error (action error or field error depending on the type of validator) will be added to the ValidationContext of the object being validated.

Plain validator 优先级高于field-validator.他们定义的顺序中,先获取plain validator,后获取field-validator.一个标注为short-circuit的validator将避免对接下来validator的评估,并且添加一个error到ValidationContext中。

In the example above, the actual execution of validator would be as follows:

  1. Plain Validator 1
  2. Plain Validator 2
  3. Field Validators for email field
  4. Field Validators for email2 field

Since Field Validator 2 is short-circuited, if its validation failed, it will causes Field validators for email field and Field validators for email2 field to not be validated as well.

既然Field validator 2是短路的,如果验证失败,email 字段会验证,email2字段不会被验证。

Usefull Information: More complecated validation should probably be done in the validate() method on the action itself (assuming the action implements Validatable interface which ActionSupport already does).

有用信息:更复杂的验证应该在Action类里的validate方法中实现。(假设action实现了validatable接口,这个validatable接口被actionSupport实现)

A plain Validator (non FieldValidator) that gets short-circuited will completely break out of the validation stack no other validators will be evaluated and plain validator takes precedence over field validator meaning that they get evaluated in the order they are defined before field validator gets a chance to be evaludated again according to their order defined.


Short cuircuiting and validator flavours

A FieldValidator that gets short-circuited will only prevent other FieldValidators for the same field from being evaluated. Note that this "same field" behavior applies regardless of whether the or syntax was used to declare the validation rule. By way of example, given this -validation.xml file:

<validator type="required" short-circuit="true">
<param name="fieldName">bar</param>
<message>You must enter a value for bar.</message>
</validator>

<validator type="expression">
<param name="expression">foo gt bar</param>
<message>foo must be great than bar.</message>
</validator>

both validators will be run, even if the "required" validator short-circuits. "required" validators are FieldValidator's and will not short-circuit the plain ExpressionValidator because FieldValidators only short-circuit other checks on that same field. Since the plain Validator is not field specific, it is not short-circuited.

两个validator都在运行,尽管“required”validator短路。“required”validators 是FieldValidator 不能短路掉plain Expression Validator。因为FieldValidator仅仅能短路掉自己字段的validator。既然palin validator不是field规格的,所以它不会被短路掉。

How Validators of an Action are Found

As mentioned above, the framework will also search up the inheritance tree of the action to find default validations for interfaces and parent classes of the Action. If you are using the short-circuit attribute and relying on default validators higher up in the inheritance tree, make sure you don't accidentally short-circuit things higher in the tree that you really want!

正如上面提到的,框架将搜索action的继承树,来查为接口和action父类的默认验证。如果你用short-circuit attribute  并且依赖继承树上高层的默认验证,确保你不要意外地短路掉高层继承树里那些你真正想要的东西。

Resources

WebWork Validation

posted on 2007-04-27 11:30 MingIsMe 阅读(1445) 评论(0)  编辑  收藏 所属分类: Struts2学习

 
Powered by:
BlogJava
Copyright © MingIsMe