Spring Validation

简单说明

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

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

简单配置

首先引入相应的依赖

        
            org.hibernate.validator
            hibernate-validator
            6.0.13.Final
        

        
            org.jboss.logging
            jboss-logging
            3.3.2.Final
        

        
            javax.validation
            validation-api
            2.0.1.Final
        

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

   

    

    
    
        
        
    

其中为 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 Validation)