Form Validation in JSP-Servlet


On the Eclipse, create a Maven project

Click Next button to select Workspace Location for project

Click Next button to select Archetype for project

Click Next button and enter Project Information:

  • Group Id: LearnJSPServletWithRealApps
  • Artifact Id: LearnJSPServletWithRealApps
  • Package: com.demo

Click Finish button to finish create Maven project




<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>LearnJSPServletWithRealApps</groupId>
	<artifactId>LearnJSPServletWithRealApps</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Learn JSP-Servlet with Real Apps</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>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>6.0.13.Final</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>LearnJSPServletWithRealApps</finalName>
	</build>
</project>
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

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

Create new JSP file named index.jsp in src\main\webapp folder. This file will redirect to DemoServlet as below:

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

Create new package named com.demo.entities. In this package, create new java class named Account.java as below:

package com.demo.entities;

import javax.validation.constraints.Email;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.URL;

public class Account implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

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

	@NotEmpty
	@Length(min = 3, max = 10)
	public String getUsername() {
		return this.username;
	}

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

	@NotEmpty
	@Pattern(regexp = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})")
	public String getPassword() {
		return this.password;
	}

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

	@NotNull
	@Min(18)
	@Max(120)
	public int getAge() {
		return this.age;
	}

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

	@NotEmpty
	@Email
	public String getEmail() {
		return this.email;
	}

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

	@URL
	public String getWebsite() {
		return this.website;
	}

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

}




Create new package named com.demo.servlets. In this package, create new Servlet named AccountServlet as below:

package com.demo.servlets;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.demo.entities.Account;

@WebServlet("/account")
public class AccountServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public AccountServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("account/index.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Account account = new Account();
			account.setUsername(request.getParameter("username"));
			account.setPassword(request.getParameter("password"));
			account.setAge(Integer.parseInt(request.getParameter("age")));
			account.setEmail(request.getParameter("email"));
			account.setWebsite(request.getParameter("website"));

			ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
			Validator validator = validatorFactory.getValidator();
			Set<ConstraintViolation<Account>> constraintViolations = validator.validate(account);
			if (!constraintViolations.isEmpty()) {
				String errors = "<ul>";
				for (ConstraintViolation<Account> constraintViolation : constraintViolations) {
					errors += "<li>" + constraintViolation.getPropertyPath() + " " + constraintViolation.getMessage()
							+ "</li>";
				}
				errors += "</ul>";
				request.setAttribute("account", account);
				request.setAttribute("errors", errors);
				request.getRequestDispatcher("account/index.jsp").forward(request, response);
			} else {
				request.setAttribute("account", account);
				request.getRequestDispatcher("account/success.jsp").forward(request, response);
			}
		} catch (Exception e) {
			request.setAttribute("errors", e.getMessage());
			request.getRequestDispatcher("account/index.jsp").forward(request, response);
		}

	}

}

Create new folder named account in src\main\webapp folder. In this folder, create new JSP files as below:

In src\main\webapp\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" isELIgnored="false"%>
<html>
<head>
<title>Register</title>
</head>
<body>

	<h3>Register Account</h3>
	${errors }
	<form method="post" action="${pageContext.request.contextPath }/account">
		<table cellpadding="2" cellspacing="2">
			<tr>
				<td>Username</td>
				<td><input type="text" name="username" value="${account.username }"></td>
			</tr>
			<tr>
				<td>Password</td>
				<td><input type="password" name="password" value="${account.password }"></td>
			</tr>
			<tr>
				<td>Age</td>
				<td><input type="text" name="age" value="${account.age }"></td>
			</tr>
			<tr>
				<td>Email</td>
				<td><input type="text" name="email" value="${account.email }"></td>
			</tr>
			<tr>
				<td>Website</td>
				<td><input type="text" name="website" value="${account.website }"></td>
			</tr>
			<tr>
				<td>&nbsp;</td>
				<td><input type="submit" value="Save"></td>
			</tr>
		</table>
	</form>

</body>
</html>

In src\main\webapp\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"%>
<html>
<head>
<title>Register</title>
</head>
<body>

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

</body>
</html>




Select project, right click and select Run As/Run on Server menu

Access DemoServlet with following urls as below:

  • http://localhost:8081/LearnJSPServletWithRealApps
  • http://localhost:8081/LearnJSPServletWithRealApps/account

Output

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

Output

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

Output