问题
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:
- Per Action class: in a file named
ActionName-validation.xml
- Per Action alias: in a file named
ActionName-alias-validation.xml
- 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:
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.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