Newsletter |
XML Validations In Struts2 With Examples
Let us see the XML validations in struts2, we used to call this type of validations as declarative, what ever. In struts2 if we want to apply the declarative validations then we need to use a set of per-defined validation rules, that are given by the framework. All pre-defined rules are configured in an xml file called validators.xml. In struts2 along with jar files added in the application, this validators.xml file also will be loaded automatically. If we want to create any custom validators (user defined) then we need to copy validators.xml into classes folder of our web application and then we need to configure our validator into validators.xml, if we don’t want any custom validations then no need to copy this validators.xml into classes folder.
If we want to apply xml validations for client inputs then we can do it in the following 2 ways.
- By creating a validation.xml file for our Action class
- By creating a validation.xml file for an Action alias
Actually if we have multiple business methods exist in an action class then we configure the same action for multiple times.
Example:
Let our action class name MyAction, and we have setters, getters with 2 business methods execute1() and execute2(), as if we are going to get 2 types of validations on the same variables, like for Admin, User.
- If my url is, loginuser.do then my validations file name will be MyAction-loginuser-validator.xml
- If my url is, loginadmin.do then my xml file must be MyAction-loginadmin-validator.xml
In struts.xml
We need to configure our Action class 2 times but we will specify the execute() method name like…
<action name="/loginuser.do" class="MyAction" method="execute1" > -- - --- - - ------- - --- -- </action> <action name="/loginadmin.do" class="MyAction" method="execute2" > -- - --- - - ------- - --- -- </action>
Note: This is the case if we want to apply separate validations for same input values, if we want single set of validations, then xml file name will be MyAction-validator.xml
If we want to apply single time xml validations for our action class then our xml file name should be
(Action class name)-validation.xml
If we want to apply different set of validations on same action class like Admin,User then xml file name should be
(Action class name)-Alias-validation.xml
Remember: We need to store our validation xml files in the classes folder of the web application
Syntax of our validation.xml in struts2
--- dtd --- <validators> <field name="firstName"> <field-validator type="rule name"> <message> some message </message> </field> </field> </validators>
You Might Also Like
::. About the Author .:: | ||
All the topics have nicely described. Great Job…
Thanks @java4s
how to validate a image file in struts2?
can u explain about struts with sql server integration ?
well described