HTML 5 Forms Validation in Struts 2

On the Eclipse, create a Maven project

Click Next button and select Workspace location for project

Click Next button and select maven-archetype-webapp

Click Next button and enter Project Information:

  • GroupId: LearnStrutsFrameworkWithRealApps
  • Artifact Id: LearnStrutsFrameworkWithRealApps
  • Package: com.demo

Click Finish button to finish create Maven project




Select current project, Right click and select Properties menu. In Properties dialog, select Targeted Runtime in left side after select Tomcat server from server list in right side

Click Ok button to finish

Select current project, Right click and select Build Path\Configure Build Path menu Select JRE System Library in Libraries tab:

Click Edit button and select JRE System Library you need use as below:

Click Finish button to finish




Open pom.xml file and add configurations for Struts 2 as below:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>LearnStrutsFrameworkWithRealApps</groupId>
	<artifactId>LearnStrutsFrameworkWithRealApps</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>LearnStrutsFrameworkWithRealApps Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>1.2.1</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- Struts 2 Framework -->

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.5.20</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>2.5.20</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>LearnStrutsFrameworkWithRealApps</finalName>
	</build>

</project>




Open web.xml file in src\main\webapp\WEB-INF folder and add configurations for Struts 2 as below:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
		 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Learn Struts 2 Framework with Real Apps</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<init-param>
			<param-name>struts.devMode</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>struts.action.extension</param-name>
			<param-value>html</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

Create new properties file named errors.properties in src/main/resources folder as below:

errors.invalid=${getText(fieldName)} is invalid.
errors.required=${getText(fieldName)} is required.
errors.number=${getText(fieldName)} must be a number.
errors.email=${getText(fieldName)} must be a valid email
errors.url=${getText(fieldName)} must be a valid url
errors.range=${getText(fieldName)} is not in the range ${min} and ${max}.
errors.rangestring=Please enter a value between ${minLength} and ${maxLength} characters long.
errors.existing=Username is exist
errors.password=${getText(fieldName)} is invalid.




Create new xml file named struts.xml in src/main/resources folder as below:

<!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.custom.i18n.resources" value="errors" />

</struts>

Create new package named entities. In this package, create new java classes as below:

In entities package, create new java class named Account.java as below:

package entities;

import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.UrlValidator;

public class Account {

	private String username;
	private String password;
	private String email;
	private String website;
	private int age;

	@RequiredStringValidator(key = "errors.required", trim = true)
	@StringLengthFieldValidator(key = "errors.rangestring", minLength = "3", maxLength = "10", trim = true)
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@RequiredStringValidator(key = "errors.required", trim = true)
	@RegexFieldValidator(key = "errors.password", regexExpression = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})", trim = true)
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@RequiredStringValidator(key = "errors.required", trim = true)
	@EmailValidator(key = "errors.email")
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@UrlValidator(key = "errors.url")
	public String getWebsite() {
		return website;
	}

	public void setWebsite(String website) {
		this.website = website;
	}

	@IntRangeFieldValidator(key = "errors.range", min = "18", max = "120")
	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}




Create new package named controllers.action in src/main/java folder. The action class in Struts 2 must be put in a package named action. In this package, create new java class named AccountAction.java as below:

package controllers.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.interceptor.validation.SkipValidation;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;

import entities.Account;

@Namespace("/account")
public class AccountAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private Account account;

	@VisitorFieldValidator
	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	@SkipValidation
	@Action(value = "index", results = {
		@Result(name = SUCCESS, location = "/WEB-INF/views/account/index.jsp")
	})
	public String index() {
		this.account = new Account();
		this.account.setAge(18);
		return SUCCESS;
	}

	@Action(value = "save", results = {
		@Result(name = INPUT, location = "/WEB-INF/views/account/index.jsp"),
		@Result(name = SUCCESS, location = "/WEB-INF/views/account/success.jsp")
	})
	public String save() {
		System.out.println("Account Information");
		System.out.println("username: " + this.account.getUsername());
		System.out.println("password: " + this.account.getPassword());
		System.out.println("email: " + this.account.getEmail());
		System.out.println("website: " + this.account.getWebsite());
		System.out.println("age: " + this.account.getAge());
		return SUCCESS;
	}

	@Override
	public void validate() {
		if(this.account.getUsername().equalsIgnoreCase("abc")) {
			addFieldError("account.username", getText("errors.existing"));
		}
	}

}




Create new folder named views in src\main\webapp\WEB-INF folder. In views folder, create new folder named account. In account folder create new views as below:

In account folder, create new JSP file named index.jsp as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Struts 2 with Real Apps</title>

<style type="text/css">
.errorMessage {
	color: red;
}
</style>

</head>
<body>

	<h3>Register</h3>
	<s:form method="post" namespace="/account" action="save">

		<s:textfield label="Username" name="account.username" required="required" placeholder="Input your username" minlength="3" maxlength="10"></s:textfield>

		<s:password label="Password" name="account.password"  required="required" placeholder="Input your password"
				pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
				title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters"></s:password>

		<s:textfield label="Email" name="account.email" required="required" placeholder="Input your email" path="email"></s:textfield>

		<s:textfield label="Website" name="account.website" placeholder="Input your website" path="website"></s:textfield>

		<s:textfield label="Age" name="account.age" type="number" min="18" max="50" step="1" required="required" placeholder="Input your age"></s:textfield>

		<s:submit value="Save" align="left"></s:submit>

	</s:form>

</body>
</html>

In account folder create new JSP file named success.jsp as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Struts 2 with Real Apps</title>
</head>
<body>

	<h3>Account Information</h3>
	<table border="1">
		<tr>
			<td>Username</td>
			<td>${account.username }</td>
		</tr>
		<tr>
			<td>Password</td>
			<td>${account.password }</td>
		</tr>
		<tr>
			<td>Email</td>
			<td>${account.email }</td>
		</tr>
		<tr>
			<td>Website</td>
			<td>${account.website }</td>
		</tr>
		<tr>
			<td>Age</td>
			<td>${account.age }</td>
		</tr>
	</table>

</body>
</html>




Create new jsp file named index.jsp in src\main\webapp folder as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="account/index.html"></jsp:forward>

Select project, right click and select Run on Server menu

Access index method in account action with following url:

http://localhost:8080/LearnStrutsFrameworkWithRealApps/account/index.html

Output

Click Save button submit form to AccountAction with some instances of invalid data as below:

Case 1

Case 2

Click Save button submit form to AccountAction with some instances of valid data as below:

Output