Struts 2 : Apply different XML validation files to one Action Methods

别来无恙 提交于 2019-12-10 15:46:24

问题


I'm new in Struts 2 Framework, and I've used the XML validation file to validate the fields of a form. My question is:

  • How can I Apply different XML validation files to the Methods of one Action ?

  • I also wants to use the same XML validation file for more than one method of the action .


回答1:


  • Q: How can I Apply different XML validation files to the Methods of one Action ?

You can create an XML validation file for each method of the Action, by using Action Alias naming convention, (instead of the default Action Class one).

From the docs:

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

[...]

In this context, "Action Alias" refers to the action name as given in the Struts configuration. Often, the name attribute matches the method name, but they may also differ.


  • Q: I also wants to use the same XML validation file for more than one method of the action .

You can proceed in a lot of ways. Keeping in mind that one Action should perform "one action" or so, and that you shouldn't have too many methods in a single Action, be aware that:

  1. If you are validating a custom object (or a Collection of them, for example) instead of multiple single fields in the Action, you can use the Visitor Validator. It will require you to put an XML file with ObjectClassName-validation.xml in the object folder (not in the Action one), and will be reused by every Action (or alias) validating it.

  2. You could otherwise mess with the hierarchy, playing with action extension and adding a method on each level, creating in the end multiple XML validation files, but it will be overkill and fundamentally wrong (it would be preferable to create multiple single-method actions at the same level).

Then stick to the Alias way, the Visitor way, and try keeping your actions small...



来源:https://stackoverflow.com/questions/23779970/struts-2-apply-different-xml-validation-files-to-one-action-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!