Spring Validation

简单说明

前端发送到后端的数据即使经过了 JavaScript 的校验,但有可能任然有人试使用专门的工具向后端发送恶意数据。

当面对前端发生到后端的数据,我们也要进行校验。

简单配置

首先引入相应的依赖

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

        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
            <version>3.3.2.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>

并在 Spring 配置文件中进行配置

   <mvc:annotation-driven conversion-service="conversionService" validator="validator"/>

    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"/>

    <!-- 校验器 -->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
        <property name="validationMessageSource" ref="messageSource"/>
    </bean>

其中为 POJO 采用注解方式定义校验规则

public class Student {
    @NotNull(message = "student.onlineId.notnull")
    private int onlineId;

    @NotBlank(message = "student.studentType.notnull")
    private String studyType;

    @NotNull(message = "student.startStudyTime.notnull")
    private long startStudyTime;

    //省略 setter 和 getter
}

简单使用

使用 Spring MVC Restful 接口

    //插入一个学生
    @ResponseBody
    @RequestMapping(value = "/student", method = RequestMethod.POST)
    public Map insertStudent(@RequestBody @Validated Student student, BindingResult result) {

        if (result.hasErrors()) {
            String errorMessage = result.getFieldError().getDefaultMessage();
            //业务代码,忽略不看
            String msg = messageSource.getMessage(errorMessage, null, Locale.CHINA);
            return responseTo.msg("failed");
        } else {
            studentService.insertStudent(student);
            return responseTo.msg("success");
        }

    }

这里的主要使用是在方法的参数

(@Validated  Student student, BindingResult result)

@Validated 表示要校验的对象,而校验规则我们前面已经写在 Student 类中了, result 是校验结果
通过使用

result.hasErrors();

来判断是否有错误

 result.getFieldError().getDefaultMessage();

来返回一个错误信息.

当然有可能配置了多个校验规则
Spring 的方式是会把所有校验规则都过一遍,出现多个错误会返回一个 List

result.getFieldErrors();

这个方法返回多个错误实例

最后我们可以根据这个校验结果进行处理了

参考资料:使用spring validation完成数据后端校验

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,055评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,408评论 19 139
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,472评论 2 59
  • 看慕芝评: 慕芝可以吃吗 为什么总在这里粗现 当然不可以 慕芝是Graceland简书上的经纪人 代理他的漫画和爆...
    Graceland阅读 3,287评论 5 4
  • 三日后,便是今年的端阳节了。 说及此,似是已经闻到了家家粽香…… 记忆里的端阳节离不开一个土制的灶台和一口大大的锅...
    樱桃一个果阅读 1,053评论 0 2