Spring MVC-07循序渐进之验证器 上 (Spring自带的验证框架)

简介: Spring MVC-07循序渐进之验证器 上 (Spring自带的验证框架)

概述


SpringMVC中有两种方式可以进行验证输入

  • 利用Spring自带的验证框架
  • 利用JSR 303实现

本篇博文我们将分别讲述这两种输入验证方法


验证概览


Converter和Formatter作用域Field级。 在MVC应用程序中,它们将String转换或者格式化成另外一种Java类型,比如java.util.Date.


验证器则作用于object级。它决定某一个对象中的所有field是否均是有效的,以及是否遵循某些规则。


那么,思考一个问题如果一个应用程序中即使用了Formatter也使用了validator ,则他们的事件顺序是怎么的呢?


在调用Controller期间,将会有一个或者多个Formatter,视图将输入字符串转换成domain对象的field值,一旦格式化成功,则验证器就会介入。


Spring验证器


Spring的输入验证甚至早于JSR 303(Java验证规范),尽管对于新的项目,一般建议使用JSR303验证器

为了创建Spring验证器,需要实现org.springframework.validation.Validator接口。

接口源码如下

public interface Validator {
    boolean supports(Class<?> clazz);
    void validate(Object target, Errors errors);
}


supports:验证器可以处理可以处理指定的Class ,supports方法将返回true。 validate方法会验证目标对象,并将验证错误填入Errors对象

Errors对象是org.springframework.validation.Errors接口的一个实例,包含了一系列FieldError和ObjectError对象


编写验证器,不需要直接创建Error对象,因为实例化ObjectError或者FieldError。 大多数时候,只给reject或者rejectValue方法传入一个错误码,Spring就会在属性文件中查找错误码没回去相应的错误消息, 还可以传入一个默认的消息,当没有找到指定的错误码时,就会使用默认消息


Errors对象中的错误消息可以利用表单标签库的Errors标签显示在页面中, 错误消息可以通过Spring支持的国际化特性本地化。


ValidationUtils类


org.springframework.validation.ValidationUtils是一个工具类,有助于编写Spring验证器

方法如下


20180226190632114.png

Spring验证器Demo


2018022619075193.png


这个demo中,我们使用了一个ProductValidator的验证器,用于验证Product对象。

Product类

package com.artisan.domain;
import java.io.Serializable;
import java.util.Date;
public class Product implements Serializable {
    private static final long serialVersionUID = 748392348L;
    private String name;
    private String description;
    private Float price;
    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;
    }
}


验证器类

package com.artisan.validator;
import java.util.Date;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.artisan.domain.Product;
/**
 * 
 * @ClassName: ProductValidator
 * @Description: 实现Validator接口,对Product进行校验
 * @author Mr.Yang
 * @date 2018年2月26日
 *
 */
public class ProductValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Product.class.isAssignableFrom(clazz);
    }
    @Override
    public void validate(Object target, Errors errors) {
        // 强制转成校验对象
        Product product = (Product) target;
        // 校验必填字段
        ValidationUtils.rejectIfEmpty(errors, "name", "productname.required");
        ValidationUtils.rejectIfEmpty(errors, "price", "price.required");
        ValidationUtils.rejectIfEmpty(errors, "productionDate", "productiondate.required");
        // 校验price
        Float price = product.getPrice();
        if (price != null && price < 0) {
            errors.rejectValue("price", "price.negative");
        }
        // 校验productionDate
        Date productionDate = product.getProductionDate();
        if (productionDate != null) {
            // The hour,minute,second components of productionDate are 0
            if (productionDate.after(new Date())) {
                errors.rejectValue("productionDate", "productiondate.invalid");
            }
        }
    }
}


ProductValidator是一个非常简单的校验器,它的validate方法校验Product方法是否有名称和价格,且价格不能为负数,它还会确保生产日期不能晚于今天的日期。


源文件


验证器不需要显式注册,但是如果想从某个属性文件中获取错误消息,则需要通过声明messageSourceBean,告诉Spring去哪里查找这个文件

完整的SpringMVC的配置文件如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd     
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描控制层的注解,使其成为Spring管理的Bean -->
    <context:component-scan base-package="com.artisan.controller"/>
    <!-- 静态资源文件 -->
    <mvc:annotation-driven  conversion-service="conversionService"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/*.jsp" location="/"/>
    <!-- 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <bean id="messageSource" 
            class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/resource/messages" />
    </bean>
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="formatters">
            <set>
                <bean class="com.artisan.formatter.DateFormatter">
                    <constructor-arg type="java.lang.String" value="MM-dd-yyyy" />
                </bean>
            </set>
        </property>
    </bean>
</beans>

国际化资源文件 messages.properties

productname.required=Please enter a product name
price.required=Please enter a price
price.negative=Please enter a price > 0
productiondate.required=Please enter a production date
productiondate.invalid=Invalid production date. Please ensure the production date is not later than today.


Controller类


在Controller类中通过实例化validator类,就可以使用Spring验证器了。为了校验改验证器是否生成错误的消息,需要找BindingResult中调用hasErrors方法


package com.artisan.controller;
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 com.artisan.domain.Product;
import com.artisan.validator.ProductValidator;
@Controller
@RequestMapping("/product")
public class ProductController {
     private static final Logger logger = Logger.getLogger(ProductController.class);
     @RequestMapping(value = "/product_input")
        public String inputProduct(Model model) {
            model.addAttribute("product", new Product());
            return "ProductForm";
        }
        @RequestMapping(value = "/product_save")
        public String saveProduct(@ModelAttribute Product product,
                BindingResult bindingResult, Model model) {
            logger.info("product_save");
            // 校验Product
            ProductValidator productValidator = new ProductValidator();
            productValidator.validate(product, bindingResult);
            if (bindingResult.hasErrors()) {
                FieldError fieldError = bindingResult.getFieldError();
                logger.info("Code:" + fieldError.getCode() + ", field:" + fieldError.getField());
                return "ProductForm";
            }
            // save product here
            model.addAttribute("product", product);
            return "ProductDetails";
        } 
}

使用Spring验证器的第二种方式: 在Controller中编写initBinder方法,并将验证器传到WebDataBinder ,并调用validate方法

@org.springframework.web.bind.annotation.InitBinder
public void initBinder(WebDataBinder binder){
    // this will apply the validator  to all request-handling methods
    binder.setValidator(new ProductValidator());
    binder.validate();
}


将验证器传到WebDataBinder,会使该验证器应用于Controller类中所有请求的方法。


或者利用@javax.validation.Valid对要验证的对象参数进行标注

public String saveProduct(@Valid @ModelAttribute Product product,BindingResult bindingResult,Model model){
}


Valid是JSR303中定义的,下篇博文将介绍。


测试验证器

什么都不输入的情况下


20180226192500976.png


价格输入一个小于0 , 时间输入一个大于今天的日期


20180226192809421.png

输入正确的结果


20180226193048352.png


源码

代码已提交到github

https://github.com/yangshangwei/SpringMvcTutorialArtisan

相关文章
|
3月前
|
安全 Java Ruby
我尝试了所有后端框架 — — 这就是为什么只有 Spring Boot 幸存下来
作者回顾后端开发历程,指出多数框架在生产环境中难堪重负。相比之下,Spring Boot凭借内置安全、稳定扩展、完善生态和企业级支持,成为构建高可用系统的首选,真正经受住了时间与规模的考验。
269 2
|
2月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
4月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
2月前
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
128 8
|
3月前
|
监控 Kubernetes Cloud Native
Spring Batch 批处理框架技术详解与实践指南
本文档全面介绍 Spring Batch 批处理框架的核心架构、关键组件和实际应用场景。作为 Spring 生态系统中专门处理大规模数据批处理的框架,Spring Batch 为企业级批处理作业提供了可靠的解决方案。本文将深入探讨其作业流程、组件模型、错误处理机制、性能优化策略以及与现代云原生环境的集成方式,帮助开发者构建高效、稳定的批处理系统。
395 1
|
5月前
|
安全 Java 微服务
Java 最新技术和框架实操:涵盖 JDK 21 新特性与 Spring Security 6.x 安全框架搭建
本文系统整理了Java最新技术与主流框架实操内容,涵盖Java 17+新特性(如模式匹配、文本块、记录类)、Spring Boot 3微服务开发、响应式编程(WebFlux)、容器化部署(Docker+K8s)、测试与CI/CD实践,附完整代码示例和学习资源推荐,助你构建现代Java全栈开发能力。
572 0
|
4月前
|
Cloud Native Java API
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
Java Spring框架技术栈选和最新版本及发展史详解(截至2025年8月)-优雅草卓伊凡
772 0
|
5月前
|
缓存 安全 Java
第五章 Spring框架
Spring IOC(控制反转)通过工厂模式管理对象的创建与生命周期,DI(依赖注入)则让容器自动注入所需对象,降低耦合。常见注解如@Component、@Service用于声明Bean,@Autowired用于注入。Bean默认单例,作用域可通过@Scope配置,如prototype、request等。Spring通过三级缓存解决循环依赖问题,但构造函数循环依赖需用@Lazy延迟加载。AOP通过动态代理实现,用于日志、事务等公共逻辑。事务通过@Transactional实现,需注意异常处理及传播行为。
89 0
|
5月前
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
180 0
|
5月前
|
存储 缓存 NoSQL
Spring Cache缓存框架
Spring Cache是Spring体系下的标准化缓存框架,支持多种缓存(如Redis、EhCache、Caffeine),可独立或组合使用。其优势包括平滑迁移、注解与编程两种使用方式,以及高度解耦和灵活管理。通过动态代理实现缓存操作,适用于不同业务场景。
446 0