springboot默认集成jackson,当前端使用application/json向后台传参时,便可以使用@Valid +jackson的注解 进行参数的校验,遵循JSR 303规范(Java Specification Requests 规范提案),是JAVA EE 6中的一项子规范,一套JavaBean参数校验的标准,叫做Bean Validation。JSR 303用于对Java Bean中的字段的值进行验证,Spring MVC 3.x之中也大力支持 JSR-303,可以在控制器中对表单提交的数据方便地验证。
javax.validation.constraints 包中常用注解
@Null 被注释的元素必须为null
@NotNull 被注释的元素不能为null
@AssertTrue 被注释的元素必须为true
@AssertFalse 被注释的元素必须为false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max,min) 被注释的元素的大小必须在指定的范围内。
@Digits(integer,fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式。
@Email 被注释的元素必须是电子邮件地址
@Length 被注释的字符串的大小必须在指定的范围内
@NotEmpty 被注释的字符串必须非空
@Range 被注释的元素必须在合适的范围内
实例:
接受参数的dto类:
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
public class RemoveDeviceDto {
@NotBlank(message = "工单id不能为空")
@JsonProperty(value = "workNum")
private String orderId;
@NotNull(message = "企业id不能为空")
private Long businessId;
@NotBlank(message = "设备序列号不能为空")
private String deviceSn;
}
spring绑定参数时会使用jackson自动对应字段,比如上面代码的 @JsonProperty(value = "workNum") 注解
控制器方法
@PostMapping("/wechat/business-device-delete")
public String deleteDeviceFromBusiness(@Valid @RequestBody RemoveDeviceDto dto, BindingResult result){
if (result.hasErrors()){
return result.getFieldError().getDefaultMessage();
}
return "123";
}
@Valid 不能写在方法上,要写在参数前,同时绑定对象时需要用到@RequestBody ,否则参数不能自动绑定到vo类,
BindingResult result 要紧随其后,作为绑定的结果,使用hasErrors 方法判断是否绑定成功, result.getFieldError().getDefaultMessage(),输出绑定失败的错误信息(vo类中,注解括号里的message信息)
拓展:
BindingResult 接口继承了Error接口
BindingResult 源码如下:
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.validation;
import java.beans.PropertyEditor;
import java.util.Map;
import org.springframework.beans.PropertyEditorRegistry;
/**
* General interface that represents binding results. Extends the
* {@link Errors interface} for error registration capabilities,
* allowing for a {@link Validator} to be applied, and adds
* binding-specific analysis and model building.
*
* <p>Serves as result holder for a {@link DataBinder}, obtained via
* the {@link DataBinder#getBindingResult()} method. BindingResult
* implementations can also be used directly, for example to invoke
* a {@link Validator} on it (e.g. as part of a unit test).
*
* @author Juergen Hoeller
* @since 2.0
* @see DataBinder
* @see Errors
* @see Validator
* @see BeanPropertyBindi