Recommended: Sing it, brah! 5 fabulous songs for developers
JW's Top 5
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 4 of 6
Once a custom validator is written it needs to be registered with Struts 2. The validators.xml file, which must be present in WEB-INF/classes, contains definitions of all custom validators in the Web application. Listing 9 shows the custom validator configuration:
<validators>
<validator name="genderValidator" class="struts2validation.GenderValidator"/>
</validators>
Once Struts 2 knows about the custom validator, it can be used in the validation configuration. Listing 10 shows the gender validator added to the action validation configuration:
<field name="gender">
<field-validator type="genderValidator">
<message>Joe is not a Female</message>
</field-validator>
</field>
Not all methods in a Struts 2 action get validated. As I mentioned already, you can specifically annotate action methods to
skip validation. Also, you can instruct the validation interceptor to exclude methods with an excludeMethods parameter from validation. The defaultStack (from struts-default.xml) sets a number of predefined method names to be excluded from validation: input, back, cancel, and browse.
In situations when the initial form display depends on data generated by an action, you must exclude certain methods from the validation process. In this case the struts.xml definition could look like Listing 11:
<action name="First_*" method="{1}" class="struts2validation.FirstAction">
<interceptor-ref name="defaultStack"/>
<result name="input">/FirstInput.jsp</result>
<result name="female">/Female.jsp</result>
<result>/Male.jsp</result>
</action>
Listing 11 makes it possible to access the FirstInput.jsp form through an action with a URL of FirstAction_input.action. The
input method needs to return input (which is the default input implementation in the ActionSupport class). The <form> tag must reflect the change in action name:
<s:form action="First_" theme="xhtml">
Now the logic from the input action method will be executed with no preceding validation.
More