使用springboot 自带框架进行 controller层参数校验

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.
 *
 * 

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 BeanPropertyBindingResult * @see DirectFieldBindingResult * @see MapBindingResult */ public interface BindingResult extends Errors { /** * Prefix for the name of the BindingResult instance in a model, * followed by the object name. */ String MODEL_KEY_PREFIX = BindingResult.class.getName() + "."; /** * Return the wrapped target object, which may be a bean, an object with * public fields, a Map - depending on the concrete binding strategy. */ Object getTarget(); /** * Return a model Map for the obtained state, exposing a BindingResult * instance as '{@link #MODEL_KEY_PREFIX MODEL_KEY_PREFIX} + objectName' * and the object itself as 'objectName'. *

Note that the Map is constructed every time you're calling this method. * Adding things to the map and then re-calling this method will not work. *

The attributes in the model Map returned by this method are usually * included in the {@link org.springframework.web.servlet.ModelAndView} * for a form view that uses Spring's {@code bind} tag in a JSP, * which needs access to the BindingResult instance. Spring's pre-built * form controllers will do this for you when rendering a form view. * When building the ModelAndView instance yourself, you need to include * the attributes from the model Map returned by this method. * @see #getObjectName() * @see #MODEL_KEY_PREFIX * @see org.springframework.web.servlet.ModelAndView * @see org.springframework.web.servlet.tags.BindTag */ Map getModel(); /** * Extract the raw field value for the given field. * Typically used for comparison purposes. * @param field the field to check * @return the current value of the field in its raw form, * or {@code null} if not known */ Object getRawFieldValue(String field); /** * Find a custom property editor for the given type and property. * @param field the path of the property (name or nested path), or * {@code null} if looking for an editor for all properties of the given type * @param valueType the type of the property (can be {@code null} if a property * is given but should be specified in any case for consistency checking) * @return the registered editor, or {@code null} if none */ PropertyEditor findEditor(String field, Class valueType); /** * Return the underlying PropertyEditorRegistry. * @return the PropertyEditorRegistry, or {@code null} if none * available for this BindingResult */ PropertyEditorRegistry getPropertyEditorRegistry(); /** * Add a custom {@link ObjectError} or {@link FieldError} to the errors list. *

Intended to be used by cooperating strategies such as {@link BindingErrorProcessor}. * @see ObjectError * @see FieldError * @see BindingErrorProcessor */ void addError(ObjectError error); /** * Resolve the given error code into message codes. *

Calls the configured {@link MessageCodesResolver} with appropriate parameters. * @param errorCode the error code to resolve into message codes * @return the resolved message codes */ String[] resolveMessageCodes(String errorCode); /** * Resolve the given error code into message codes for the given field. *

Calls the configured {@link MessageCodesResolver} with appropriate parameters. * @param errorCode the error code to resolve into message codes * @param field the field to resolve message codes for * @return the resolved message codes */ String[] resolveMessageCodes(String errorCode, String field); /** * Mark the specified disallowed field as suppressed. *

The data binder invokes this for each field value that was * detected to target a disallowed field. * @see DataBinder#setAllowedFields */ void recordSuppressedField(String field); /** * Return the list of fields that were suppressed during the bind process. *

Can be used to determine whether any field values were targeting * disallowed fields. * @see DataBinder#setAllowedFields */ String[] getSuppressedFields(); }

 

Error接口源码如下:

/*
 * 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.util.List;

import org.springframework.beans.PropertyAccessor;

/**
 * Stores and exposes information about data-binding and validation
 * errors for a specific object.
 *
 * 

Field names can be properties of the target object (e.g. "name" * when binding to a customer object), or nested fields in case of * subobjects (e.g. "address.street"). Supports subtree navigation * via {@link #setNestedPath(String)}: for example, an * {@code AddressValidator} validates "address", not being aware * that this is a subobject of customer. * *

Note: {@code Errors} objects are single-threaded. * * @author Rod Johnson * @author Juergen Hoeller * @see #setNestedPath * @see BindException * @see DataBinder * @see ValidationUtils */ public interface Errors { /** * The separator between path elements in a nested path, * for example in "customer.name" or "customer.address.street". *

"." = same as the * {@link org.springframework.beans.PropertyAccessor#NESTED_PROPERTY_SEPARATOR nested property separator} * in the beans package. */ String NESTED_PATH_SEPARATOR = PropertyAccessor.NESTED_PROPERTY_SEPARATOR; /** * Return the name of the bound root object. */ String getObjectName(); /** * Allow context to be changed so that standard validators can validate * subtrees. Reject calls prepend the given path to the field names. *

For example, an address validator could validate the subobject * "address" of a customer object. * @param nestedPath nested path within this object, * e.g. "address" (defaults to "", {@code null} is also acceptable). * Can end with a dot: both "address" and "address." are valid. */ void setNestedPath(String nestedPath); /** * Return the current nested path of this {@link Errors} object. *

Returns a nested path with a dot, i.e. "address.", for easy * building of concatenated paths. Default is an empty String. */ String getNestedPath(); /** * Push the given sub path onto the nested path stack. *

A {@link #popNestedPath()} call will reset the original * nested path before the corresponding * {@code pushNestedPath(String)} call. *

Using the nested path stack allows to set temporary nested paths * for subobjects without having to worry about a temporary path holder. *

For example: current path "spouse.", pushNestedPath("child") -> * result path "spouse.child."; popNestedPath() -> "spouse." again. * @param subPath the sub path to push onto the nested path stack * @see #popNestedPath */ void pushNestedPath(String subPath); /** * Pop the former nested path from the nested path stack. * @throws IllegalStateException if there is no former nested path on the stack * @see #pushNestedPath */ void popNestedPath() throws IllegalStateException; /** * Register a global error for the entire target object, * using the given error description. * @param errorCode error code, interpretable as a message key */ void reject(String errorCode); /** * Register a global error for the entire target object, * using the given error description. * @param errorCode error code, interpretable as a message key * @param defaultMessage fallback default message */ void reject(String errorCode, String defaultMessage); /** * Register a global error for the entire target object, * using the given error description. * @param errorCode error code, interpretable as a message key * @param errorArgs error arguments, for argument binding via MessageFormat * (can be {@code null}) * @param defaultMessage fallback default message */ void reject(String errorCode, Object[] errorArgs, String defaultMessage); /** * Register a field error for the specified field of the current object * (respecting the current nested path, if any), using the given error * description. *

The field name may be {@code null} or empty String to indicate * the current object itself rather than a field of it. This may result * in a corresponding field error within the nested object graph or a * global error if the current object is the top object. * @param field the field name (may be {@code null} or empty String) * @param errorCode error code, interpretable as a message key * @see #getNestedPath() */ void rejectValue(String field, String errorCode); /** * Register a field error for the specified field of the current object * (respecting the current nested path, if any), using the given error * description. *

The field name may be {@code null} or empty String to indicate * the current object itself rather than a field of it. This may result * in a corresponding field error within the nested object graph or a * global error if the current object is the top object. * @param field the field name (may be {@code null} or empty String) * @param errorCode error code, interpretable as a message key * @param defaultMessage fallback default message * @see #getNestedPath() */ void rejectValue(String field, String errorCode, String defaultMessage); /** * Register a field error for the specified field of the current object * (respecting the current nested path, if any), using the given error * description. *

The field name may be {@code null} or empty String to indicate * the current object itself rather than a field of it. This may result * in a corresponding field error within the nested object graph or a * global error if the current object is the top object. * @param field the field name (may be {@code null} or empty String) * @param errorCode error code, interpretable as a message key * @param errorArgs error arguments, for argument binding via MessageFormat * (can be {@code null}) * @param defaultMessage fallback default message * @see #getNestedPath() */ void rejectValue(String field, String errorCode, Object[] errorArgs, String defaultMessage); /** * Add all errors from the given {@code Errors} instance to this * {@code Errors} instance. *

This is a onvenience method to avoid repeated {@code reject(..)} * calls for merging an {@code Errors} instance into another * {@code Errors} instance. *

Note that the passed-in {@code Errors} instance is supposed * to refer to the same target object, or at least contain compatible errors * that apply to the target object of this {@code Errors} instance. * @param errors the {@code Errors} instance to merge in */ void addAllErrors(Errors errors); /** * Return if there were any errors. */ boolean hasErrors(); /** * Return the total number of errors. */ int getErrorCount(); /** * Get all errors, both global and field ones. * @return List of {@link ObjectError} instances */ List getAllErrors(); /** * Are there any global errors? * @return {@code true} if there are any global errors * @see #hasFieldErrors() */ boolean hasGlobalErrors(); /** * Return the number of global errors. * @return the number of global errors * @see #getFieldErrorCount() */ int getGlobalErrorCount(); /** * Get all global errors. * @return List of ObjectError instances */ List getGlobalErrors(); /** * Get the first global error, if any. * @return the global error, or {@code null} */ ObjectError getGlobalError(); /** * Are there any field errors? * @return {@code true} if there are any errors associated with a field * @see #hasGlobalErrors() */ boolean hasFieldErrors(); /** * Return the number of errors associated with a field. * @return the number of errors associated with a field * @see #getGlobalErrorCount() */ int getFieldErrorCount(); /** * Get all errors associated with a field. * @return a List of {@link FieldError} instances */ List getFieldErrors(); /** * Get the first error associated with a field, if any. * @return the field-specific error, or {@code null} */ FieldError getFieldError(); /** * Are there any errors associated with the given field? * @param field the field name * @return {@code true} if there were any errors associated with the given field */ boolean hasFieldErrors(String field); /** * Return the number of errors associated with the given field. * @param field the field name * @return the number of errors associated with the given field */ int getFieldErrorCount(String field); /** * Get all errors associated with the given field. *

Implementations should support not only full field names like * "name" but also pattern matches like "na*" or "address.*". * @param field the field name * @return a List of {@link FieldError} instances */ List getFieldErrors(String field); /** * Get the first error associated with the given field, if any. * @param field the field name * @return the field-specific error, or {@code null} */ FieldError getFieldError(String field); /** * Return the current value of the given field, either the current * bean property value or a rejected update from the last binding. *

Allows for convenient access to user-specified field values, * even if there were type mismatches. * @param field the field name * @return the current value of the given field */ Object getFieldValue(String field); /** * Return the type of a given field. *

Implementations should be able to determine the type even * when the field value is {@code null}, for example from some * associated descriptor. * @param field the field name * @return the type of the field, or {@code null} if not determinable */ Class getFieldType(String field); }

==================================================================================

如果认为这篇文章帮到了你,那就请领个红包打赏下吧

 

你可能感兴趣的:(java,controller,springboot)