In the tutorial Struts Form Validation Basic Example (Using XML), we show you how to use XML elements to configure field validators for a login form. This tutorial is going to achieve similar thing but using annotations instead of XML. In addition, we’ll use Struts convention plug-in to map URLs with actions and results implicitly by convention, rather than using XML in struts.xml file.

To remind, we will develop a sample Struts2 application that presents a login form whose fields will be validated using annotation configuration.

 

1. Struts Form Validation Annotations

It’s very easy to use an annotation type to specify validation rule for a form’s field in Struts, just by annotating setter method of the field in action class or in a JavaBean model class. For example:

@RequiredStringValidator(message = "Please enter your name.")
public void setName(String name) {
	this.name = name;
}
In the code snippet above, the setter method is annotated by the @RequiredStringValidator annotation which will ensure that the user doesn’t leave the field empty when submitting the form. The text message “Please enter your name.” will be shown in case validation fails. Some other validation annotations provided by Struts are:

    • RequiredFieldValidator
    • EmailFieldValidator
    • DateRangeFieldValidator
    • ExpressionValidator
For a complete list, see: Struts validation annotations.

Let’s build the sample application. Create a Java dynamic web project in Eclipse IDE with the following structure:

Struts2 Form Validation Annotations Eclipse project

Add the following Struts jar files into the WEB-INF\lib folder:

    • asm-3.3.jar
    • asm-commons-3.3.jar
    • asm-tree-3.3.jar
    • commons-fileupload-1.3.jar
    • commons-io-2.0.1.jar
    • commons-lang3-3.1.jar
    • commons-logging-1.1.3.jar
    • commons-logging-api-1.1.jar
    • freemarker-2.3.19.jar
    • javassist-3.11.0.GA.jar
    • ognl-3.0.6.jar
    • struts2-convention-plugin-2.3.15.1.jar
    • struts2-core-2.3.15.1.jar
    • xwork-core-2.3.15.1.jar


NOTES: There is no struts.xml file in this project because we use naming convention for action class, JSP files and URLs mapping. Thus the struts2-convention-plugin-2.3.15.1.jar must be present in the classpath.

 

2. Coding Input Form

Create login-input.jspfile underWEB-INF\content folder with the following content:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Form - Struts2 Validation Example (Annotations)</title>
</head>
<body>
	<div align="center">
		<h2>Login</h2>
		<h3>Struts2 Validation Example (Using Annotations)</h3>
		<s:form action="login" method="post" validate="true">
			<s:textfield label="E-mail" name="email" />
			<s:password label="Password" name="password" />
			<s:submit value="Login" />
		</s:form>
	</div>
</body>
</html>
We can see that this page presents a login form with two fields: email and password. The attribute validate=”true” of the <s:form> tag specifies that Struts will generate Javascript code to perform client-side validation for this form.

 

3. Coding Struts Action Class with Validation Annotations

Create LoginAction.java file under package net.codejava.struts with the following code:

package net.codejava.struts;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;

public class LoginAction extends ActionSupport {
	private String email;
	private String password;

	public String execute() {
		if (email != null && email.equals("admin@codejava.net")) {
			return SUCCESS;			
		} else {
			return INPUT;
		}
	}
	
	@RequiredStringValidator(message = "Please enter your e-mail address.")
	@EmailValidator(message = "Please enter a valid e-mail address.")
	public void setEmail(String email) {
		this.email = email;
	}
	
	@RequiredStringValidator(message = "Please enter your password.")
	public void setPassword(String password) {
		this.password = password;
	}
	
	public String getEmail() {
		return email;
	}
	
	public String getPassword() {
		return password;
	}
}
The action method execute() will redirect the client to SUCCESS page if the e-mail equals to admin@codejava.net, or to the INPUT page otherwise. Notice that the setters of the fields email and password are annotated by two validation annotation types @RequiredStringValidator and @EmailValidator to specify validation rules and error messages for those fields.

  • For the email field:
    @RequiredStringValidator(message = "Please enter your e-mail address.")
    @EmailValidator(message = "Please enter a valid e-mail address.")
    public void setEmail(String email) {
    	this.email = email;
    }
     

  • For the password field:
    @RequiredStringValidator(message = "Please enter your password.")
    public void setPassword(String password) {
    	this.password = password;
    } 
 

4. Coding Success Page

Create login-success.jsp file underWEB-INF\content folder with the following content:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Success</title>
</head>
<body>
	<div align="center">
		<h2>Welcome, you have logged in successfully!</h2>
	</div>
</body>
</html>
The action class will redirect the client to this page if the login form passes validation checks as the user enters the desired e-mail address and a password.

 

5. Testing the Sample Struts Form Validation Application

Type the following URL into web browser:

http://localhost:8080/Struts2ValidationBasicAnnotations/login-input

The login form gets displayed:

Test Struts2 form validation using annotations

Leave both fields empty and hit Login button, validation error messages appear above the fields like this:

Test Struts2 form validation using annotations - fields empty

Try to enter a wrong-formatted email address and an arbitrary password:

Test Struts2 form validation using annotations - invalid email

Now try to enter the email as admin@codejava.net with an arbitrary password:

Test Struts2 form validation using annotations - success

Voila, that works! Download the Eclipse project and ready-to-deploy WAR file in the Attachments section below.

 

Related Struts Form Validation Tutorials:

 

Other Struts Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (Struts2ValidationBasicAnnotations.war)Struts2ValidationBasicAnnotations.war[Deployable WAR file]3597 kB
Download this file (Struts2ValidationBasicAnnotations.zip)Struts2ValidationBasicAnnotations.zip[Eclipse project]3602 kB

Add comment

   


Comments 

#2Jake2015-11-09 08:23
Hi,
Didn't you forget to map your action "login-success" with success.jsp, in case of SUCCESS?HAW
Quote
#1nikhil2015-01-04 05:48
how to remove error of annottion,?

im begginer and im getting error line under any@ annotation.. :/
Quote