Spring MVC-07循序渐进之验证器 下 (JSR 303验证)

简介: Spring MVC-07循序渐进之验证器 下 (JSR 303验证)

概述


JSR303”Bean Validation” 和 JSR349 “Bean Validation 1.1”指定了一整套的API,通过标注对象属性添加约束。

当然了JSR 只是一个规范文档,目前有两个实现


  • Hibernate Validator
  • Apache BVal (仅实现了JSR303)

这里我们使用 Hibernate Validator来演示

JSR303 不需要编写验证器,但是要利用JSR30标注类型嵌入约束.

JSR 303约束如下


image.png


一旦了解了JSR303 validation的使用方法,使用起来比Spring验证器还要容易。 同使用Spring验证器一样,同样可以在属性文件中以下列格式使用property键来覆盖来自JSR303验证器的错误消息

constraint.object.property


JSR 303 Validator Demo

20180226195057834.png

同Spring Validator不同在于,它没有ProductValidator类,其次,需要添加Maven依赖

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


Product 类中标注了JSR 303注解

package com.artisan.domain;
import java.io.Serializable;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
public class Product implements Serializable {
    private static final long serialVersionUID = -5379168879247929742L;
    @Size(min=1,max=10)
    private String name;
    private String description;
    private float price;
    @NotNull
    @Past
    private Date productionDate;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    public Date getProductionDate() {
        return productionDate;
    }
    public void setProductionDate(Date productionDate) {
        this.productionDate = productionDate;
    }
}


在ProductController类的productSave方法中,必须用@Valid对Product参数进行标注

package com.artisan.controller;
import javax.validation.Valid;
import org.apache.log4j.Logger;
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 com.artisan.domain.Product;
@Controller
@RequestMapping(value = "/product")
public class ProductController {
    private static final Logger logger = Logger.getLogger(ProductController.class);
    @RequestMapping(value = "/product_input", method = RequestMethod.GET)
    public String productInput(Model model) {
        model.addAttribute("product", new Product());
        return "ProductForm";
    }
    /**
     * 
    * @Title: productSave  
    * @Description: 标注了@Valid 对product进行校验
    * @param @param product
    * @param @param bindingResult
    * @param @param model
    * @param @return    参数  
    * @return String    返回类型  
    * @throws
     */
    @RequestMapping(value = "/product_save", method = RequestMethod.POST)
    public String productSave(@Valid @ModelAttribute Product product, 
            BindingResult bindingResult, Model model) {
        // 校验
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            logger.info("Code:" + fieldError.getCode() + " ,field:" + fieldError.getField());
            return "ProductForm";
        }
        // simulate save product here
        model.addAttribute("product", product);
        model.addAttribute("message", "add successfully");
        return "ProductView";
    }
}


为了定制来自验证器的错误消息,要在messages.properties文件中使用两个键

Size.product.name=Product name must be in 1 to 10 characters long
Past.product.productionDate=Production date must a past date
NotNull.product.productionDate=Production date must not be null


测试


什么都不输入


20180226195623698.png

输入一个将来的时间


20180226195743764.png

可见JSR 303 验证起了作用。


总结

由于JSR 303是正式的Java规范,因此建议新的项目使用JSR 303 验证器


源码

代码已提交到github

https://github.com/yangshangwei/SpringMvcTutorialArtisan

相关文章
|
11月前
|
缓存 监控 Java
深入了解Spring中的JSR 303验证和拦截器
深入了解Spring中的JSR 303验证和拦截器
94 0
|
3月前
|
算法 Java API
在Spring Boot中实现接口签名验证通常涉及以下步骤
在Spring Boot中实现接口签名验证通常涉及以下步骤
215 4
|
2月前
|
Java 数据库连接 测试技术
在Spring Boot中实现数据校验与验证
在Spring Boot中实现数据校验与验证
|
10月前
|
缓存 前端开发 Java
【SpringMVC】JSR 303与拦截器注解使用
【SpringMVC】JSR 303与拦截器注解使用
61 0
|
存储 前端开发 Java
Spring MVC 中的数据绑定和验证机制是什么,如何使用
Spring MVC 中的数据绑定和验证机制是什么,如何使用
|
4月前
|
存储 Java Maven
SpringCloud Oauth2.0 实现资源验证
SpringCloud Oauth2.0 实现资源验证
53 0
|
10月前
|
监控 前端开发 Java
学习 [Spring MVC] 的JSR 303和拦截器,提高开发效率
学习 [Spring MVC] 的JSR 303和拦截器,提高开发效率
43 0
|
12月前
|
前端开发 Java 数据库连接
【SpringMVC】JSR 303与interceptor拦截器快速入门
JSR 303是Java规范请求(Java Specification Request)的缩写,意思是Java 规范提案。是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。 JSR-303 是JAVA EE 6 中的一项子规范,叫做Bean Validation,Hibernate Validator 是 Bean Validation 的参考实现 . Hibe
|
1月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
31 0
|
4月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
148 0