SpringbootValidation es fácil de usar

Este blog es más básico y completo, pero aún no entiendo la Validación personalizada

Suplemento:

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

Entender

@Validated solo se puede agregar al controlador, es inútil agregarlo a otras capas de servicio, no se puede informar incorrectamente

Si se produce un error, se informará un error BindException. BindException tiene un método para obtener todos los errores, estos errores son de clase ObjectError. Tiene el método más importante: getDefaultMessage para obtener el mensaje de error.

Segunda vez: ya sé cómo personalizar las anotaciones de verificación:

1. Cree una clase de anotación personalizada: @interface

Esto es mio

package com.imooc.miaosha.validator;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {IsMobileValidator.class })//关联到哪个注解类
public @interface  IsMobile {
	//这些都是注解的参数
	boolean required() default true;//我自己加的
	
	String message() default "手机号码格式错误";//如果校验不通过默认提示的信息

	Class<?>[] groups() default { };//先不管

	Class<? extends Payload>[] payload() default { };//先不管
}

¿Cómo escribirlo? Referencia directa a lo que ya está allí: hice clic en la anotación NotNull para ver su implementación:

/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 javax.validation.constraints;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * The annotated element must not be {@code null}.
 * Accepts any type.
 *
 * @author Emmanuel Bernard
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { })
public @interface NotNull {

	String message() default "{javax.validation.constraints.NotNull.message}";

	Class<?>[] groups() default { };

	Class<? extends Payload>[] payload() default { };

	/**
	 * Defines several {@link NotNull} annotations on the same element.
	 *
	 * @see javax.validation.constraints.NotNull
	 */
	@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
	@Retention(RUNTIME)
	@Documented
	@interface List {

		NotNull[] value();
	}
}

En realidad es muy simple

1. Copié estas líneas de código:
Inserte la descripción de la imagen aquí
y:
Inserte la descripción de la imagen aquí
Las funciones de estas líneas de código se han escrito en los comentarios sobre mi código con más detalle.
Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí

2. Luego cree la clase de validador: implemente la lógica de juicio

package com.imooc.miaosha.validator;
import  javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;

import com.imooc.miaosha.util.ValidatorUtil;

public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {

	private boolean required = false;
	//constraintAnnotation 这个参数就是上面定义的注解,这里给传过来了
	public void initialize(IsMobile constraintAnnotation) {
		//于是我可以拿到这个注解传过来的参数,交给我的成员变量。在下面的isValid方法中可以用到
		required = constraintAnnotation.required();
	}
	//这个方法参数中的value是被注解所作用到的成员属性
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if(required) {
			return ValidatorUtil.isMobile(value);//这是我编写的一个判断工具类,逻辑是如果符合手机格式就返回true
		}else {
			if(StringUtils.isEmpty(value)) {
				return true;
			}else {
				return ValidatorUtil.isMobile(value);
			}
		}
	}

}


Vea a continuación aquí, esta restricción La anotación es la anotación misma.

Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí
Para los genéricos aquí, IsMobile es el nombre de la anotación, que es el @IsMobile personalizado. La cadena se refiere a qué tipo de atributo de miembro se aplica la anotación.
Inserte la descripción de la imagen aquí
Aquí está String, entonces:
Inserte la descripción de la imagen aquí
aquí está String

Verificación de un solo parámetro: el controlador no siempre se puede pasar a una entidad

1. Agregue al controlador: @Validated (esto no afecta a los @Validated agregados en el método)
2. Inserte la descripción de la imagen aquí
3. Si el error se arroja aquí no es BindException sino: ConstraintViolationException.

56 artículos originales publicados · Me gusta1 · Visitas1509

Supongo que te gusta

Origin blog.csdn.net/weixin_44841849/article/details/105175508
Recomendado
Clasificación