Spring Bean Validation Example with JSR-303 Annotations
2015-08-31 16:01
633 查看
JSR-303 bean validation is a specification whose objective is to standardize the validation of Java beans through annotations. The objective of the JSR-303 standard is to use annotations directly in a Java bean class. This allows validation rules to be specified directly in the code they are intended to validate, instead of creating validation rules in separate classes. So far we learned about validations in spring mvc using
After applying the validation, error messages on front UI will look like this:
Spring MVC JSR 303 Validation Annotations Example
For validation to actually work, you need an implementation as well, such as Hibernate Validator.
1) Include validator reference to controller class so that you can access it across all methods in controller.
2) Next change is in controller’s post method which is called when user submit the form.
Please note that unlike the earlier Spring specific validation approaches, the validator field is not assigned to any bean, but rather a factory class of the type
In
Once the validation process is complete, a loop is declared over the violations Set to extract any possible validation errors encountered in the
1) Enter URL : http://localhost:8080/springmvcexample/employee-module/addNew It will display blank form.
Spring MVC Form Example – Blank Form
2) Without filling any field, submit the form. You will get error specific to each field.
Spring MVC JSR 303 Validation Annotations Example
3) Fill all fields and press Submit button. Success page will be displayed.
Spring MVC Form Example – Success Message
For reference, complete
And
BindingResult.rejectValue()and custom validator implementation. In this example we will learn about validating spring managed beans using annotations based on the JSR-303 standard.
After applying the validation, error messages on front UI will look like this:
Spring MVC JSR 303 Validation Annotations Example
Adding JSR-303 and Hibernate Validator Dependency
To use JSR-303 annotations with Spring, you will need to add below dependency inpom.xml.
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency>
For validation to actually work, you need an implementation as well, such as Hibernate Validator.
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency>
Applying JSR-303 Annotations
After adding JSR-303 dependencies, the first thing you need to do is decorate a Java bean with the necessary JSR-303 annotations. See belowEmployeeVOclass whose fields are annotated with annotations such as
@Sizeand
@Pattern.
package com.howtodoinjava.demo.model; import java.io.Serializable; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; public class EmployeeVO implements Serializable { private static final long serialVersionUID = 1L; private Integer id; @Size(min = 3, max = 20) private String firstName; @Size(min = 3, max = 20) private String lastName; @Pattern(regexp=".+@.+\\.[a-z]+") private String email; //Setters and Getters @Override public String toString() { return "EmployeeVO [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]"; } }
Controller changes
To apply this validator, you need to perform the following modification to your controller.1) Include validator reference to controller class so that you can access it across all methods in controller.
private Validator validator;
2) Next change is in controller’s post method which is called when user submit the form.
@RequestMapping(method = RequestMethod.POST) public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO, BindingResult result, SessionStatus status) { Set<ConstraintViolation<EmployeeVO>> violations = validator.validate(employeeVO); for (ConstraintViolation<EmployeeVO> violation : violations) { String propertyPath = violation.getPropertyPath().toString(); String message = violation.getMessage(); // Add JSR-303 errors to BindingResult // This allows Spring to display them in view via a FieldError result.addError(new FieldError("employee",propertyPath, "Invalid "+ propertyPath + "(" + message + ")")); } if (result.hasErrors()) { return "addEmployee"; } // Store the employee information in database // manager.createNewRecord(employeeVO); // Mark Session Complete status.setComplete(); return "redirect:addNew/success"; }
Please note that unlike the earlier Spring specific validation approaches, the validator field is not assigned to any bean, but rather a factory class of the type
javax.validation.ValidatorFactory. This is how JSR-303 validation works. The assignment process is done inside the controller’s constructor.
In
submitForm()method, the first step consists of creating a Set of the type
javax.validation.ConstraintViolationto hold any errors detected from validating the instance of the
EmployeeVOobject. The value assigned to this Set results from executing
validator.validate(employeeVO), which is used to run the validation process on the
employeeVOfield that is an instance of the
EmployeeVOobject.
Once the validation process is complete, a loop is declared over the violations Set to extract any possible validation errors encountered in the
EmployeeVOobject. Since the violations Set contains JSR-303 specific errors, it’s necessary to extract the raw error messages and place them in a Spring MVC specific format. This allows validation errors to be displayed in a view managed by Spring as if they are generated by a Spring validator.
Test the Application
That’s all. JSR-303 validation configuration is complete. Now test the application.1) Enter URL : http://localhost:8080/springmvcexample/employee-module/addNew It will display blank form.
Spring MVC Form Example – Blank Form
2) Without filling any field, submit the form. You will get error specific to each field.
Spring MVC JSR 303 Validation Annotations Example
3) Fill all fields and press Submit button. Success page will be displayed.
Spring MVC Form Example – Success Message
For reference, complete
pom.xmlfile is 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>com.howtodoinjava.demo</groupId>
<artifactId>springmvcexample</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>springmvcexample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- Tag libs support for view layer -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
<scope>runtime</scope>
</dependency>
<!-- JSR 303 Dependencies -->
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.0.0.GA</version> </dependency>
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.1.Final</version> </dependency>
</dependencies>
<build>
<finalName>springmvcexample</finalName>
</build>
</project>
And
EmployeeControllerclass is as below:
package com.howtodoinjava.demo.controller;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.howtodoinjava.demo.model.EmployeeVO;
import com.howtodoinjava.demo.service.EmployeeManager;
@Controller
@RequestMapping("/employee-module/addNew")
@SessionAttributes("employee")
public class EmployeeController {
@Autowired
EmployeeManager manager;
private Validator validator;
public EmployeeController()
{
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
validator = validatorFactory.getValidator();
}
@RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model) {
EmployeeVO employeeVO = new EmployeeVO();
model.addAttribute("employee", employeeVO);
return "addEmployee";
}
@RequestMapping(method = RequestMethod.POST) public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO, BindingResult result, SessionStatus status) { Set<ConstraintViolation<EmployeeVO>> violations = validator.validate(employeeVO); for (ConstraintViolation<EmployeeVO> violation : violations) { String propertyPath = violation.getPropertyPath().toString(); String message = violation.getMessage(); // Add JSR-303 errors to BindingResult // This allows Spring to display them in view via a FieldError result.addError(new FieldError("employee",propertyPath, "Invalid "+ propertyPath + "(" + message + ")")); } if (result.hasErrors()) { return "addEmployee"; } // Store the employee information in database // manager.createNewRecord(employeeVO); // Mark Session Complete status.setComplete(); return "redirect:addNew/success"; }
@RequestMapping(value = "/success", method = RequestMethod.GET)
public String success(Model model) {
return "addSuccess";
}
}
相关文章推荐
- java普通算法
- Java 7之多线程第1篇 - 线程的状态转换
- java security 的jdk的工具
- JavaWeb中的四大域对象
- java集合中对象某属性比较排序Comparable与Comparator
- leetcode Roman to Integer java基本编程学习(四)
- Spring MVC Display, Validate and Submit Form Example
- Spring MVC上传文件的两种方式
- fail to create java virtual machine..
- spring data jpa 配置
- java security接口和类的分布
- 常用的JavaXML解析技术
- JSch - Java实现的SFTP(文件上传详解篇)
- Java中使用jcraft进行SFTP的上传下载
- java 日期相减时分秒
- CRC32之JAVA实现
- [转]Spring Security 可动态授权RBAC权限模块实践
- spring监听器ContextLoaderListener的疑问
- Java IO体系中常用的流分类
- 如何使用Struts 2防止表单重复提交?