Validation Groups in Spring MVC


On the Eclipse, create a Spring MVC project in Spring Boot

Enter Project Information:

  • Name: LearnSpringMVCWithRealApps
  • Group: com.demo
  • Artifact: LearnSpringMVCWithRealApps
  • Description: Learn Spring MVC with Real Apps
  • Package: com.demo

Select the technologies and libraries to be used:

  • Web

Click Next button to show Site Information for project

Click Finish button to finish create Spring MVC project

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.demo</groupId>
	<artifactId>LearnSpringMVCWithRealApps</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>LearnSpringMVCWithRealApps</name>
	<description>Learn Spring MVC with Real Apps</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<!-- Spring MVC  -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- JSTL tag lib -->
		<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>

		<!-- Tomcat for JSP rendering -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>




Create new properties file, named messages.properties in src\main\resources folder. This file contains error messages for validation.

NotEmpty=This field is required.
Length=Please enter a value between {2} and {1} characters long.
Min=Please enter a value greater than or equal to {1}.
Max=Please enter a value less than or equal to {1}.
NotNull=This field is required.
account.username.exists=Username already exists.
typeMismatch.int=Please enter a valid number.
URL.website=Please enter a valid URL.
Email=Please enter a valid email address.
StrongPassword=Password does not meet complexity requirements.
typeMismatch={0} is of invalid format.
Pattern={0} must match pattern for complexity requirements.
spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**

server.port=9596
package com.demo;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class SpringMVCConfiguration extends WebMvcConfigurerAdapter {

	@Bean
	public MessageSource messageSource() {
		ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
		resourceBundleMessageSource.setBasename("messages");
		return resourceBundleMessageSource;
	}

}




In com.demo.entities package, create validation groups as below:

Create new java interface, named Group1.java

package com.demo.entities;

public interface Group1 {
}

Create new java interface, named Group2.java

package com.demo.entities;

public interface Group2 {
}

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

Create new java class, named Account.java

package com.demo.entities;

import org.hibernate.validator.constraints.NotEmpty;

public class Account {

	@NotEmpty(groups = { Group1.class, Group2.class })
	private String username;

	@NotEmpty(groups = { Group1.class })
	private String password;

	public String getUsername() {
		return username;
	}

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

	public String getPassword() {
		return password;
	}

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

}

Create new package named com.demo.validators. In this package, create new validator named AccountValidator as below:

package com.demo.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.demo.entities.Account;

public class AccountValidator implements Validator {

	@Override
	public boolean supports(Class arg0) {
		return Account.class.equals(arg0);
	}

	@Override
	public void validate(Object object, Errors errors) {
	}

}




Create new package named com.demo.controllers. In this package, create new controller named AccountController as below:

package com.demo.controllers;

import org.springframework.stereotype.*;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.demo.entities.Account;
import com.demo.entities.Group1;
import com.demo.entities.Group2;
import com.demo.validators.AccountValidator;

@Controller
@RequestMapping("account")
public class AccountController {

	@RequestMapping(value = "register", method = RequestMethod.GET)
	public String register(ModelMap modelMap) {
		modelMap.put("account", new Account());
		return "account/register";
	}

	@RequestMapping(value = "register", method = RequestMethod.POST)
	public String register(@Validated({ Group1.class }) @ModelAttribute("account") Account account,
			BindingResult bindingResult, ModelMap modelMap) {
		AccountValidator accountValidator = new AccountValidator();
		accountValidator.validate(account, bindingResult);
		if (bindingResult.hasErrors()) {
			return "account/register";
		} else {
			modelMap.put("account", account);
			return "account/success1";
		}
	}

	@RequestMapping(value = "edit", method = RequestMethod.GET)
	public String edit(ModelMap modelMap) {
		modelMap.put("account", new Account());
		return "account/edit";
	}

	@RequestMapping(value = "edit", method = RequestMethod.POST)
	public String edit(@Validated({ Group2.class }) @ModelAttribute("account") Account account,
			BindingResult bindingResult, ModelMap modelMap) {
		AccountValidator accountValidator = new AccountValidator();
		accountValidator.validate(account, bindingResult);
		if (bindingResult.hasErrors()) {
			return "account/edit";
		} else {
			modelMap.put("account", account);
			return "account/success2";
		}
	}

}

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

Create new jsp file named register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Account Register</title>
</head>
<body>

	<h3>Account Register</h3>
	<s:form method="post" commandName="account"
		action="${pageContext.request.contextPath }/account/register">
		<table cellpadding="2" cellspacing="2">
			<tr>
				<td>Username</td>
				<td><s:input path="username" /></td>
				<td><s:errors path="username"></s:errors></td>
			</tr>
			<tr>
				<td>Password</td>
				<td><s:password path="password" /></td>
				<td><s:errors path="password"></s:errors></td>
			</tr>
			<tr>
				<td>&nbsp;</td>
				<td><input type="submit" value="Save"></td>
			</tr>
		</table>
	</s:form>

</body>
</html>

Create new jsp file named success1.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success 1 Page</title>
</head>
<body>

	<h3>Success 1 Page</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>
	</table>

</body>
</html>

Create new jsp file named edit.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Update Account</title>
</head>
<body>

	<h3>Update Account</h3>
	<s:form method="post" commandName="account"
		action="${pageContext.request.contextPath }/account/edit">
		<table cellpadding="2" cellspacing="2">
			<tr>
				<td>Username</td>
				<td><s:input path="username" /></td>
				<td><s:errors path="username"></s:errors></td>
			</tr>
			<tr>
				<td>Password</td>
				<td><s:password path="password" /></td>
				<td><s:errors path="password"></s:errors></td>
			</tr>
			<tr>
				<td>&nbsp;</td>
				<td><input type="submit" value="Save"></td>
			</tr>
		</table>
	</s:form>

</body>
</html>

Create new jsp file named success2.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success 2 Page</title>
</head>
<body>

	<h3>Success 2 Page</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>
	</table>

</body>
</html>




Select LearnSpringMVCWithRealAppsApplication.java file in com.demo package, right click and select Run As/Spring Boot App menu

Validate with Group 1

Access register method in account controller with following url: http://localhost:9596/account/register

Output

Click Save button submit form to register method in account controller with invalid data as below:

Output

Click Save button submit form to register method in account controller with valid data

Output

Validate with Group 2

Access edit method in account controller with following url: http://localhost:9596/account/edit

Output

Click Save button submit form to edit method in account controller with invalid data as below:

Output

Click Save button submit form to edit method in account controller with valid data

Output

I recommend you refer to the books below to learn more about the knowledge in this article: