Spring Bean Validation Example with JSR-303 Annotations

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 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

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 in pom.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 below EmployeeVO class whose fields are annotated with annotations such as @Size and @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.ConstraintViolation to hold any errors detected from validating the instance of the EmployeeVO object. The value assigned to this Set results from executing validator.validate(employeeVO), which is used to run the validation process on the employeeVO field that is an instance of the EmployeeVO object.

Once the validation process is complete, a loop is declared over the violations Set to extract any possible validation errors encountered in the EmployeeVO object. 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

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

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

Spring MVC Form Example – Success Message

For reference, complete pom.xml file 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 EmployeeController class 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";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值