91-9990449935 0120-4256464 |
Struts 2 Custom Validation - Workflow InterceptorWe can define our own validation logic (custom validation) in struts 2 by implementing the Validateable interface in the action class. The workflow interceptor is used to get information about the error messages defined in the action class. Workflow InterceptorThe workflow interceptor checks if there is any validation errors or not. It doesn't perform any validation. It is applied when action class implements the Validateable interface. The input is the default parameter for this interceptor that determines the result to be invoked for the action or field error. It is found in the defaultStack so we don't need to define it explicitly. Parameters of workflow interceptorThere is only 1 parameter defined for workflow interceptor.
Validateabale interfaceThe Validateable interface must be implemented to perform validation logic in the action class. It contains only one method validate() that must be overridden in the action class to define the validation logic. Signature of the validate method is: ValidationAware interfaceThe ValidationAware interface can accept the field level or action class level error messages. The field level messages are kept in Map and Action class level messages are kept in collection. It should be implemented by the action class to add any error message. Methods of ValidatationAware interfaceThe methods of ValidationAware interface are as follows:
Note: ActionSupport class implements Validateable and ValidationAware interfaces, so we can inherit the ActionSupport class to define the validation logic and error messages.Steps to perform custom validationThe steps are as follows:
Example to perform custom validationIn this example, we are creating 4 pages :
1) Create index.jsp for inputThis jsp page creates a form using struts UI tags. It receives name, password and email id from the user. index.jsp2) Create the action classThis action class inherits the ActionSupport class and overrides the validate method to define the validation logic. RegisterAction.java3) Define a input result in struts.xmlThis xml file defines an extra result by the name input, that will be invoked if any error message is found in the action class. struts.xml4) Create view componentIt is the simple jsp file displaying the information of the user. welcome.jspOutputDefining action level error messageThe action level error message works for the whole form. We can define the action level error message by addActionError() method of ValidationAware interface in validate() method. For example: Now you need to use actionerror tag in index.jsp file to display the action level error message. index.jspOutput
Next TopicStruts2 Validation By Bundled Validators
|