[JAVA] Codebeispiel für OVal (annotationsbasierte Validierung FW)

Ich habe versucht, Validierungs-FW zu verwenden, die Eingabebeschränkungen durch annotationsbasierte Annotation namens OVal hinzufügen kann. Notieren Sie sich das Codebeispiel zu diesem Zeitpunkt.

Abhängigkeiten

pom.xml


<!-- https://mvnrepository.com/artifact/net.sf.oval/oval -->
<dependency>
    <groupId>net.sf.oval</groupId>
    <artifactId>oval</artifactId>
    <version>1.90</version>
</dependency>

build.gradle


// https://mvnrepository.com/artifact/net.sf.oval/oval
compile group: 'net.sf.oval', name: 'oval', version: '1.90'

Bei Verwendung mit Spring

net.sf.oval.integration.spring.SpringValidator Es scheint, dass es "org.springframework.validation.Validator" implementiert. Ich habe es noch nicht benutzt, daher werde ich es erneut melden, wenn ich es versuche.

Grundlegendes Codebeispiel

Bohnenklasse


public class SampleBean{
    /** ID */
	@Assert(expr = "null!=_value&&''!=_value", lang = "js"
//lang =Ist"bsh" / "beanshell", "groovy", or "js" / "javascript".Wählen Sie, was Sie möchten und verwenden Sie es
//Wenn es darum ging@Vielleicht hätte ich Not Empty verwenden sollen ...
    		,message="ID wird nicht eingegeben")
    private String id;

    /** No */
    private Integer no;

    /**Registrierungsdatum*/
    @Assert(expr = "null!=_value&&''!=_value", lang = "js"
    		,message="Das Registrierungsdatum wurde nicht eingegeben")
    @MatchPattern(pattern=DateUtil.DATE_MATCH_PATTERN
    		,message="Das Format des Registrierungsdatums ist seltsam"
    		,when="js:null!=_value&&''!=_value")
    @DateRange(format=DateUtil.DATE_HH_MM_FORMAT,message="Der Datumsbereich des Registrierungsdatums ist seltsam")
    @ValidateWithMethod(methodName="isValidDate", parameterType=String.class)
			,message="Bitte geben Sie das Datum Dezember ein")
    private String abcTime;

    //getter,Setter weggelassen

    private boolean isValidDate(String arg){//Ich werde erst im Dezember wahr zurückkehren
        if(arg.matches("\d{4}/12/.*")){
            return true;
        }else{
            return false;
        }
    }
}

Wie balancieren


net.sf.oval.Validator validator = new net.sf.oval.Validator();
List<ConstraintViolation> clist =  validator.validate( validatedObject );

Ich möchte mit einer statischen Methode validieren

In diesem Fall handelt es sich nicht um eine Standardfunktion. Erstellen Sie daher Ihre eigene Validierungsanmerkung und Prüfmethode. Es ist klüger, in Java8 zu schreiben, aber da ich nur die Java7-Umgebung (T-T) verwenden kann, ist es der Java7-Code.

ValidateWithStaticMethod.java(Anmerkung)


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

import net.sf.oval.ConstraintTarget;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.configuration.annotation.Constraint;
import net.sf.oval.configuration.annotation.Constraints;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE })
@Constraint(checkWith = ValidateWithStaticMethodCheck.class)
public @interface ValidateWithStaticMethod {
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD, ElementType.TYPE })
    @Constraints
    public @interface List {
        ValidateWithStaticMethod[] value();
        String when() default "";
    }

    ConstraintTarget[] appliesTo() default ConstraintTarget.CONTAINER;

    String errorCode() default "net.sf.oval.constraint.ValidateWithMethod";

    boolean ignoreIfNull() default true;

    boolean ignoreIfNullOrEmpty() default true;

    String message() default "Nachricht ist nicht definiert(ValidateWithStaticMethod)";

    Class<?> clazz();

    String methodName();

    String[] profiles() default {};

    int severity() default 0;

    String target() default "";

    String when() default "";
}

ValidateWithStaticMethodCheck.java(Überprüfen Sie die Logik)



import static net.sf.oval.Validator.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import net.sf.oval.ConstraintTarget;
import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.context.OValContext;
import net.sf.oval.exception.ReflectionException;

/**
 *Überprüfung durch statische Methode
 */
public class ValidateWithStaticMethodCheck extends AbstractAnnotationCheck<ValidateWithStaticMethod> {
    private static final long serialVersionUID = 1L;

    private final Map<Class<?>, Method> validationMethodsByClass = new WeakHashMap<Class<?>, Method>();

    private boolean ignoreIfNull;
    private boolean ignoreIfNullOrEmpty;
    private Class<?> clazz;
    private String methodName;

    @Override
    public void configure(final ValidateWithStaticMethod constraintAnnotation) {
        super.configure(constraintAnnotation);
        setMethodName(constraintAnnotation.methodName());
        setClazz(constraintAnnotation.clazz());
        setIgnoreIfNull(constraintAnnotation.ignoreIfNull());
        setIgnoreIfNullOrEmpty(constraintAnnotation.ignoreIfNullOrEmpty());
    }

    @Override
    protected Map<String, String> createMessageVariables() {
        final Map<String, String> messageVariables = getCollectionFactory().createMap(4);
        messageVariables.put("ignoreIfNull", Boolean.toString(ignoreIfNull));
        messageVariables.put("ignoreIfNullOrEmpty", Boolean.toString(ignoreIfNullOrEmpty));
        messageVariables.put("methodName", methodName);
        return messageVariables;
    }

    @Override
    protected ConstraintTarget[] getAppliesToDefault() {
        return new ConstraintTarget[] { ConstraintTarget.VALUES };
    }

    public String getMethodName() {
        return methodName;
    }

    public boolean isIgnoreIfNull() {
        return ignoreIfNull;
    }

    public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context, final Validator validator)
            throws ReflectionException {
        if (valueToValidate == null && ignoreIfNull)
            return true;
        if(ignoreIfNullOrEmpty){
        	if (valueToValidate == null)
        		return true;
        	//Wenn Sie eine leere Beurteilungsbedingung hinzufügen möchten, fügen Sie diese bitte hier hinzu
        	if ( valueToValidate instanceof String && "".equals(valueToValidate) )
        		return true;
        	if ( valueToValidate instanceof Object[] && 0==((Object[])valueToValidate).length )
        		return true;
        	if ( valueToValidate instanceof List && 0==((List<?>)valueToValidate).size() )
        		return true;
        }
        boolean result;
        Method method;
        try {
        	Class<?> parameterType = valueToValidate.getClass();
			method =  clazz.getMethod(methodName, parameterType);
	        result = (boolean)method.invoke(null, valueToValidate);
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new ReflectionException( e );
		}
        return result;
    }

    public void setIgnoreIfNull(final boolean ignoreIfNull) {
        this.ignoreIfNull = ignoreIfNull;
        requireMessageVariablesRecreation();
    }


    public void setIgnoreIfNullOrEmpty(final boolean ignoreIfNullOrEmpty) {
        this.ignoreIfNullOrEmpty = ignoreIfNullOrEmpty;
        requireMessageVariablesRecreation();
    }

	public Class<?> getClazz() {
		return clazz;
	}

	public void setClazz(Class<?> clazz) {
		this.clazz = clazz;
	}

	public void setMethodName(final String methodName) {
        this.methodName = methodName;
        synchronized (validationMethodsByClass) {
            validationMethodsByClass.clear();
        }
        requireMessageVariablesRecreation();
    }

}

Wie man kommentiert


//ValidationMethods.isFormatTelNo(String str)Codebeispiel bei Verwendung
@ValidateWithStaticMethod(clazz=ValidationMethods.class
		,methodName="isFormatTelNo"
		,message="Die Telefonnummer ist falsch. .. ..")
private String telNo;

Ich möchte dieselbe Anmerkung mehrmals hinzufügen

Es scheint, dass Sie so schreiben sollten.

@ValidateWithStaticMethod.List(value={
		@ValidateWithStaticMethod(clazz=ValidationMethods.class
				,methodName="isFormatTelNo"
				,message="Das Format der Telefonnummer ist seltsam"),
		@ValidateWithStaticMethod(clazz=ValidationMethods.class
				,methodName="isOkTelNumberSize"
				,message="Die Anzahl der Ziffern in der Telefonnummer ist falsch")
})
private String telNo;

Liste der standardmäßig bereitgestellten Anmerkungen

Recommended Posts

Codebeispiel für OVal (annotationsbasierte Validierung FW)
Federvalidierung und Fehlercode