Struts 2 Ajax Validation – jsonValidation Interceptor
Struts 2 provides support to ajax validation. In such case, page will not be refreshed or reloaded so it will make the performance fast. It is implicitly done using javascript i.e. used for the client side validation.
To use the AJAX validation, you need to add dojo plugin in your project.
jsonValidation Interceptor
The AJAX validation is performed by jsonValidation interceptor. It is not found in the default stack so we need to define it explicitly. It doesn’t perform any validation itself that is why it must be used with validation interceptor. It is found in the jsonValidationWorkflowStack, that includes jsonValidation, validation and workflow interceptors and basicstack.
Steps to perform AJAX Validation
The simple steps to perform AJAX Validation are as follows:
- create the form to get input from the user
- Inherit the ActionSupport class in your action
- Define the validation in validation.xml file
- Define result name input for the error message and register the jsonValidationWorkflowStack in struts.xml file
Example to perform ajax validation
In this example, we are creating 4 pages :
- index.jsp for input from the user.
- Register.java for business logic.
- Register-validation.xml for using bundled validators.
- struts.xml for defining the interceptors and results for the action.
- welcome.jsp for the view component.
1) Create index.jsp for input
This jsp page creates a form using struts UI tags. It receives name, password and email id from the user.
index.jsp
2) Create the action class
This action class inherits the ActionSupport class and overrides the execute method.
RegisterAction.java
3) Create the validation file
Here, we are using bundled validators to perform the validation.
Register-validation.xml
4) Create struts.xml
This xml file defines an extra result by the name input, and an interceptor jsonValidatorWorkflowStack.
struts.xml
5) Create view component
It is the simple jsp file displaying the information of the user.
welcome.jsp