Workflow Interceptor
We use the workflow interceptor to get information about the error messages defined in the action class. The Workflow Interceptor checks for any validation errors or not. The workflow interceptor is applied when the action class implements the Validateable interface.
We don't need to define the workflow interceptor explicitly; it is found in the defaultStack.
The inputResultName parameter for the workflow interceptor specifies the result name to be returned if a field error or action error is found. The input is the default parameter determining the result to be invoked for the action or field error.
Validateable Interface
We can not implement the validation logic in the action class without implementing the validateabe interface. The validateable interface contains only one method called validate() that we must override in the action class to define the validation logic.
Syntax:
public void validate();
ValidationAware Interface
The ValidationAware interface allows us to accept the action class level or feild level error messages. The field level messages are stored in Map, while the Action class level messages are held in the collection. The action class should implement the ValidationAware interface to integrate or add any error messages.
Methods
The ValidationAware Interface has multiple methods; these are:
- void addFieldError(String fieldName,String errorMessage) : The add field error method adds the specified feild's error message.
- void addActionError(String errorMessage): Adds an Action level error message for the specific action.
- void addActionMessage(String message): The add action message method adds an Action-level message for the specific action.
- void setFieldErrors(Map<String,List<String>> map): The set field error method sets a collection of error messages for fields.
- void setActionErrors(Collection<String> errorMessages): The set action error method sets a collection of error messages for this action.
- void setActionMessages(Collection<String> messages): The set action messages method sets a collection of messages for this action.
- boolean hasErrors(): Checks for any field or action errors.
- boolean hasFieldErrors(): Checks for any field errors.
- boolean hasActionErrors(): Checks for Action-level error messages.
- boolean hasActionMessages(): Checks for any Action-level messages.
- Map<String,List<String>> getFieldErrors(): This map method returns all the field level error messages.
- Collection<String> getActionErrors(): This collection method returns all the Action-level error messages.
-
Collection<String> getActionMessages(): This collection method returns all the Action-level messages.
We will use the addFieldError and addActionError method in our implementation below. So let's get straight to it.
Implementation
To implement custom validation in Struts2, we will use an algorithm that follows these four steps:
- Create the form for input from the user
- Define the validation logic in the action class by extending the ActionSupport class and overriding the validate method
- Define the result for the error message by the name input in the struts.xml file
Create index.jsp
We will create an index.jsp file that takes input from the user, like name, password, etc. This jsp page makes a form using struts UI tags.
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:actionerror/>
<s:form action="register">
<s:textfield name="name" label="Ninja Coder Name"></s:textfield>
<s:password name="password" label="Secret Password"></s:password>
<s:submit value="register"></s:submit>
</s:form>
Create the Action Class
We will create a java file named RegisterAction.java as the action class that will inherit the ActionSupport class and override the validate method to define the validation logic. The code for this file will look something like this.
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
private String name,password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void validate() {
if(name.length()<1)
addFieldError("name","Must have a Ninja Name");
if(password.length()<6)
addFieldError("password","Strong secret password must be greater than 5");
/*
if(name.trim().length()<1 || password.trim().length()<1){
addActionError("The fields can not be blank");
}*/
}
public String execute(){
//perform business logic here
return "success";
}
}
As you can see, we have used both the addFieldError and the addActionError method in this code. The action level error message from the the addActionError method works for the whole form.
Define an Input Result
We will define an input result in the struts.xml file. This XML file defines an extra result named input that invokes if any error message is found in the action class.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="abc" extends="struts-default" >
<action name="register" class="com.javatpoint.RegisterAction" >
<result name="success">/welcome.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
Create a View Component
It is a simple jsp file named welcome.jsp for displaying all the information to the user.
<%@ taglib uri="/struts-tags" prefix="s" %>
Ninja Name:<s:property value="name"/><br/>
Secret Password:<s:property value="password"/><br/>
Output
Frequently Asked Questions
How does Struts 2 validation work?
Struts 2 automatically executes the validate method when a user presses the submit button, and if any "if" statement inside the method are true, Struts 2 calls its addFieldError method. Struts 2 does not proceed to call the execute method if any errors have been added.
What does the validate() method of Actionform returns?
The validate() method returns an ActionErrors instance. If it's not null, then the validation fails. Struts 2 redisplays the form to the user and the error messages in case of failure.
What is struts 2?
Struts 2 is an open-source framework which you can use for developing web applications in Java EE.
What are the two types of validators present in the Struts2 validation framework?
The two types of validators present in the Struts 2 are:
- Field Validators
- Non-field validators
Conclusion
So we have completed our article on Custom validation in Struts2. Here, we learned about various components and concepts surrounding Custom validation and its implementation with the help of an example.
So this is the end, but don’t stop here. Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in pygame, Competitive Programming, JavaScript, System Design, and many more! If you want to test your knowledge in coding, you can check out the mock test series and participate in the contests held on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundle for placement preparations.
Nevertheless, you may consider our paid courses to give your career an edge over others!
Do upvote our blogs if you find them helpful and engaging!
Happy Learning!