简单说明
前端发送到后端的数据即使经过了 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 的方式是会把所有校验规则都过一遍,出现多个错误会返回一个 Listresult.getFieldErrors();
这个方法返回多个错误实例
最后我们可以根据这个校验结果进行处理了
网友评论