其他分享
首页 > 其他分享> > 使用Spring 3.2.0进行验证

使用Spring 3.2.0进行验证

作者:互联网

我正在使用HibernateValidator 4.3.1.整个应用程序均按预期执行验证.

我已经注册了一些自定义编辑器,以在全球范围内执行验证,例如,确保文本字段中的数值(双精度,整数等),确保有关Joda-Time API的有效日期等.

在这种类型的验证中,我通过像往常一样将allowEmpty参数设置为false来分别验证它,从而允许空值/空值,特别是在此类字段留空时显示单独的用户友好错误消息时.

因此,除了使用HibernateValidator和自定义编辑器进行验证之外,我还尝试使用以下验证策略.同样,这种验证仅适用于在空白时为自定义编辑器注册的字段.

以下是实现org.springframework.validation.Validator接口的类.

package test;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import validatorbeans.TempBean;

@Component
public final class TempValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        System.out.println("supports() invoked.");
        return TempBean.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        TempBean tempBean = (TempBean) target;

        System.out.println("startDate = " + tempBean.getStartDate() + " validate() invoked.");
        System.out.println("doubleValue = " + tempBean.getDoubleValue() + " validate() invoked.");
        System.out.println("stringValue = " + tempBean.getStringValue() + " validate() invoked.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDate", "java.util.date.nullOrEmpty.error");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "doubleValue", "java.lang.double.nullOrEmpty.error");
    }
}

该类使用@Component注释指定,​​以便可以将其自动连接到特定的Spring控制器类.调试语句完全根据用户提供的输入显示.

以下是控制器类.

package controller;

import customizeValidation.CustomizeValidation;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.groups.Default;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import test.TempValidator;
import validatorbeans.TempBean;

@Controller
public final class TempController {

    @Autowired
    private TempService tempService;

    private TempValidator tempValidator;

    public TempValidator getTempValidator() {
        return tempValidator;
    }

    @Autowired
    public void setTempValidator(TempValidator tempValidator) {
        this.tempValidator = tempValidator;
    }

    @RequestMapping(method = {RequestMethod.GET}, value = {"admin_side/Temp"})
    public String showForm(@ModelAttribute("tempBean") @Valid TempBean tempBean, BindingResult error, Map model, HttpServletRequest request, HttpServletResponse response) {
        return "admin_side/Temp";
    }

    @RequestMapping(method = {RequestMethod.POST}, value = {"admin_side/Temp"})
    public String onSubmit(@ModelAttribute("tempBean") @Valid TempBean tempBean, BindingResult errors, Map model, HttpServletRequest request, HttpServletResponse response) {
        //tempValidator.supports(TempBean.class);
        //tempValidator.validate(tempBean, errors);

        DataBinder dataBinder = new DataBinder(tempBean);
        dataBinder.setValidator(tempValidator);
        dataBinder.validate();

        //errors=dataBinder.getBindingResult();
        if (CustomizeValidation.isValid(errors, tempBean, TempBean.ValidationGroup.class, Default.class) && !errors.hasErrors()) {
            System.out.println("Validated");
        }

        return "admin_side/Temp";
    }
}

我从Spring控制器类本身(我确实想要)中调用验证器

DataBinder dataBinder = new DataBinder(tempBean);
dataBinder.setValidator(tempValidator);
dataBinder.validate();

调用了验证器,但未执行预期的验证.

如果仅使用以下语句(上面已注释掉)手动调用验证器,

tempValidator.validate(tempBean, errors);

然后执行验证.因此,我不认为我的验证器可以正常工作.为什么它不能与DataBinder一起使用?

在我的application-context.xml文件中,此bean的配置如下.

<bean id="tempValidator" class="test.TempValidator"/>

自动检测到以下许多软件包,包括其中包含TempValidator类的测试软件包.

<context:component-scan base-package="controller spring.databinder validatorbeans validatorcommands test" use-default-filters="false">
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
    <context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/>  
</context:component-scan>

我什至试图把

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

在我的dispatcher-servlet.xml文件中.

我在这里俯瞰什么?

解决方法:

如果我了解您要达到的目标-区分空白字段和​​输入的错误值-您可以使用MUCH MORE SIMPLER方法:

public class MyBean {

    @NotNull
    @DateTimeFormat(pattern="dd.MM.yyyy HH:mm") 
    private DateTime date;

    @NotNull
    @Max(value=5)
    private Integer max;

    @NotNull
    @Size(max=20)
    private String name;

    // getters, setters ... 
} 

控制器映射:

public void submitForm(@ModelAttribute @Valid MyBean myBean, BindingResult result) {

    if (result.hasErrors){
       // do something}
    else{
       // do something else
    }        
}

验证消息:

NotNull=Required field.
NotNull.date=Date is required field.
NotNull.max=Max is required field.
Size=Must be between {2} and {1} letters.
Max=Must be lower than {1}.
typeMismatch.java.lang.Integer=Must be number.
typeMismatch.org.joda.time.DateTime=Required format dd.mm.yyyy HH:mm

弹簧配置:

@Configuration
public class BaseValidatorConfig {

    @Bean
    public LocalValidatorFactoryBean getValidator() {

        LocalValidatorFactoryBean lvfb = new LocalValidatorFactoryBean();
        lvfb.setValidationMessageSource(getValidationMessageSource());
        return lvfb;
    }

    protected MessageSource getValidationMessageSource() {// return you validation messages ...}
}

如果需要,我可以提供更多详细信息和解释.

标签:hibernate-validator,spring-3,bean-validation,spring,spring-mvc
来源: https://codeday.me/bug/20191031/1974211.html