Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Struts2 validation framework


May 15, 2021 Struts2


Table of contents


In this chapter we will look at the validation framework for Struts. The validation framework in the core of Struts helps the application run rules to perform validation before executing the action method.
Client authentication is typically implemented using Javascript, but cannot rely solely on client authentication. P ractice has shown that validation should be introduced at all levels of the application framework. Let's look at two ways to add validation to a Struts project.
Let's take an example of an Employee whose name and age will be captured using a simple page, and we'll do two validations to make sure that the user always enters a name and that the age is between 28 and 65. So let's start with the JSP main page of the example.

Create a home page

Let's next write the JSP file index index for collecting information about employee.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Employee Form</title>
</head>

<body>
   <s:form action="empinfo" method="post">
      <s:textfield name="name" label="Name" size="20" />
      <s:textfield name="age" label="Age" size="20" />
      <s:submit name="submit" label="Submit" align="center" />
   </s:form>
</body>
</html>

Index .jsp the Struts tag, which we haven't learned yet, but will be learned in the relevant sections of the label. N ow, suppose the s:textfield label prints an input box and the s:submit prints a submit button. W e use the label property for each label, which is to create a label for each label.

Create a view

We'll use the JSP file .jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Success</title>
</head>
<body>
   Employee Information is captured successfully.
</body>
</html>

Create Action

So, let's define a small action class: Employee, and then add a method called validate(), as shown in the Employee .java file. M ake sure that the action class extends the ActionSupport class, otherwise the validate method will not be executed.

package cn.w3cschool.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Employee extends ActionSupport{
   private String name;
   private int age;
   
   public String execute() 
   {
       return SUCCESS;
   }
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }

   public void validate()
   {
      if (name == null || name.trim().equals(""))
      {
         addFieldError("name","The name is required");
      }
      if (age < 28 || age > 65)
      {
         addFieldError("age","Age must be in between 28 and 65");
      }
   }
}

As shown in the example above, the validation method first checks whether the Name field has a value. I f there are no values, a field Error is added to the Name field and a custom error message is displayed. S econd, check that the input values for the Age field are between 28 and 65, and if this condition is not met, we add an error above the validation field.

Profile

Finally, let's use the .xml the struts configuration file to put everything together, as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="empinfo" 
         class="cn.w3cschool.struts2.Employee"
         method="execute">
         <result name="input">/index.jsp</result>
         <result name="success">/success.jsp</result>
      </action>

   </package>

</struts>

Here's .xml the web file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">

   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

Now, right-click on the project name, and then click "Export" and "WAR File" to create a WAR file. T he WAR file is then deployed in Tomcat's webapps directory. Finally, start the Tomcat server and try to access the URL http://localhost:8080/HelloWorldStruts2/index.jsp display the following interface:

Struts2 validation framework

Now without entering any information, just click the Submit button and you'll see the following results:

Struts2 validation framework

Enter the requested information instead of the wrong class field, such as the name "text" with an age of 30, and click the Submit button to see the following interface:

Struts2 validation framework

How does this validation work?

When the user presses the submit button, Struts2 will automatically execute the validate method, and if any of the if statements listed in the method are true, Struts2 will call the addFieldError method. I f any error messages are added, Struts2 will not call the execute method. Otherwise, the Struts2 framework returns input as a result of the call operation.
Therefore, when validation fails and Struts2 returns input, the Struts2 framework reappeates the .jsp file. Because we use the form label for Struts2, Struts2 automatically adds an error message above the form field.
These error messages are the information we specify in the addFieldError method call. The addFieldError method accepts two parameters, the first is the form field name applied when the error occurs, and the second is the error message displayed above the form field.

addFieldError("name","The name is required");

To handle the return value of input, we need to add the following results to the action node .xml the struts system.

<result name="input">/index.jsp</result>

XML validation

The second way to verify is to place an xml file next to the action class. Struts2 XML-based validation provides more validation methods, such as email validation, integer range validation, form validation, expression validation, regex validation, required validation, requiredstring validation, stringlength validation, and more.
The xml file needs to be named 'action-class'-validation.xml. So, in our example, we created a file called Employee-.xml with the following:

<!DOCTYPE validators PUBLIC 
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
   <field name="name">
      <field-validator type="required">
         <message>
            The name is required.
         </message>
      </field-validator>
   </field>

   <field name="age">
     <field-validator type="int">
         <param name="min">29</param>
         <param name="max">64</param>
         <message>
            Age must be in between 28 and 65
         </message>
      </field-validator>
   </field>
</validators>

The XML file above will be saved in CLASSPATH, ideally with the class file. oyee action class without the validate() method:

package cn.w3cschool.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Employee extends ActionSupport{
   private String name;
   private int age;
   
   public String execute() 
   {
       return SUCCESS;
   }
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }
}

The rest of the settings will remain, as in the previous example. Now if you run the application, it will produce the same results as our previous example.

The advantage of using xml files to store configurations is that authentication is allowed to be separated from application code. Y ou can have developers write code and testers create xml validation files. A nother thing to note is that the authenticator is available by default. S truts has many default validators, commonly including date validators, Regex validators, and String Length authenticators. Click on the link below to learn more about the Struts2-XML Validator.