Home  >  Struts 2

Struts 2 Validation Annotation Example

By Arvind Rai, May 10, 2014
In this page we will learn how to validate a field using struts 2 annotation. In action class use annotation to validate property and enable validation in form tag in jsp. This is all that we have to do for validation in struts2 using annotation. For example I have taken a user form which consist name, email and age. We will validate these three fields.

Software Used

I have used eclipse to develop this simple user form example. Ensure below software on your system.
1. Eclipse
2. JDK 6
3. Tomcat 7

Action Class

Validation of user fields is done on property level which is bounded with html field. In the example I have used below annotations to validate the user form.
@RequiredStringValidator: Checks if any value is entered or not.
@EmailValidator: Validated email address.
@IntRangeFieldValidator: Checks if entered number is in given range or not, we need to define min and max attribute.
ResultAction.java
package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;

@Namespace("/user")
@ResultPath(value="/")
@Action(value="result", results={@Result(name="success",location="result.jsp")})
public class ResultAction extends ActionSupport{
	private String name;
	private String email;
	private int age;
	public String execute() {
	   return SUCCESS; 
	}
        @RequiredStringValidator(message = "Enter your Name.")
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@RequiredStringValidator(message = "Enter your Email.")
        @EmailValidator(message = "Enter a valid e-mail address." )
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@RequiredStringValidator(message = "Enter your age.")
	@IntRangeFieldValidator(message = "Age must be in between 18 and 30",  
             min = "18", max = "30")
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
} 
LoginAction class is used to open user form page.
LoginAction.java
package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/user")
@Action("/login")
@ResultPath(value="/")
@Result(name="success",location="login.jsp")
public class LoginAction extends ActionSupport{
	public String execute() {
	    return SUCCESS;
	}
} 



JSP Pages

In JSP page, form tag must have validate="true" attribute.
login.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head></head>
<body>
<h1>Struts 2 Validation Annotation Example</h1>
<s:form action="result" validate="true">
	<s:textfield name="name" label="Name"/>
	<s:textfield name="email" label="Email"/>
	<s:textfield name="age" label="Age"/>
	<s:submit/>
</s:form>
</body>
</html> 
Success JSP page will be as below.
result.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head></head>
<body>
<h1>Struts 2 Validation Annotation Example</h1>
<h4> Name is:  <s:property value="name"/></h4>
<h4> Email is:  <s:property value="email"/></h4>
<h4> Age is:  <s:property value="age"/></h4>
</body>
</html> 

web.xml

To run the struts 2 application, web.xml should be configured as below.
web.xml
<web-app>
  <display-name>Struts 2 Validation Annotation Example</display-name>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.concretepage.action</param-value>
        </init-param>
    </filter>
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app> 

Maven Dependency for struts 2

Find the struts 2 maven dependency to run the example.
pom.xml
<dependencies>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.3.16</version>
	</dependency>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-convention-plugin</artifactId>
		<version>2.3.8</version>
	</dependency>
</dependencies>	 

Eclipse Configuration

I have developed the example using eclipse. The struts 2 project structure in eclipse will look like as below.
Struts 2 Validation Annotation Example

Output Screen

Use http://localhost:8080/Struts2Demo-1/user/login URL to run the example. You will see a user form. To test validation, fill no field and submit. You will get the validation messages as below.
Struts 2 Validation Annotation Example
Now fill the invalid data in email and age field. Check the validation message.
Struts 2 Validation Annotation Example
Fill valid data in all field.
Struts 2 Validation Annotation Example

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us