Tutorial :Validation of certain Action's methods in Struts2


I have an Action class with CRUD actions inside and I have overridden the validate() method given by the ActionSupport class.

The question is: how can I fire the validation only for the update and create actions?

One possible solution is to move create & update on a brand new Action class, but I'd like to know if there's another solution for this.

Thanks! Roberto


I believe the two options are : refactor the validatable methods into a new action (as you said), or switch to programmatic validation (instead of declarative). Basically, call myvalidate() from inside your update/create methods, and return INPUT if there are errors.


You could also try the @SkipValidation annotation with the method you don't want to be validated:

@SkipValidation  public String yourMethod(){  ...  return SUCCESS;  }  


You can exclude the other methods by putting an exclusion in your configuration file.

<interceptor-ref name="validation">    <param name="validateAnnotatedMethodOnly">true</param>                    <param name="excludeMethods">input,back,cancel,browse</param>  </interceptor-ref>  


If you use the Struts defaultStack of interceptors, you are already excluding validation from methods called input, back, cancel, or browse.

I recommend making your own interceptor stack (default for all actions, so you don't have to re-define these things for each action). Base it on the example stack from struts-default.xml that suits you, and then edit the interceptor-ref for validation and workflow (these are closely related -- the workflow interceptor is the one that skips the action and returns the "input" action if there are validation errors -- so the method exclusions should match).

In my current project, I added in exceptions for *Form and *Input, so that validation kicks off by default, but it's easy to avoid -- just make sure the action method you're calling ends in Form or Input.

It's generally better to run validation by default (and define exceptions), because if you make a mistake and validation runs when you don't want it, you'll know immediately (your action won't execute due to errors).. whereas if you make a mistake and validation doesn't run, this is a silent failure.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »