Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

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

Ajax validation with Struts 2

Support for Ajax and JavaScript takes the pain out of Web-form validation

  • Print
  • Feedback

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:

Listing 9. 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:

Listing 10. Action validation configuration: Gender validator

 <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:

Listing 11. Struts configuration: <action> with input result

 <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.

  • Print
  • Feedback

Resources

More