java Spring 3 验证不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6227547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:56:45  来源:igfitidea点击:

Spring 3 validation not working

javavalidationspring-mvc

提问by ashishjmeshram

I have a user entity in my application which I need to validate.

我的应用程序中有一个需要验证的用户实体。

public class User {

private String userName;
private String password;

public void setUserName(String userName){
this.userName = userName;
}

public getUserName(){
return this.userName;
}   

// and so on 

}

}

For this I have created a UsersValidator like below.

为此,我创建了一个如下所示的 UsersValidator。

public class UserValidator implements Validator {

public boolean supports(Class clazz) {
    return User.class.equals(clazz);
}

public void validate(Object obj, Errors errors) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required");
}
}

and I have a controller like this

我有一个这样的控制器

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String home(@Valid User user,
        BindingResult result) {

    if (result.hasErrors()) {
        return "loginForm";
    } else {
    //continue
}

}

The binding result does not have any errors.

绑定结果没有任何错误。

What else I need to do in order for the validation to work? Do I have make any changes in the controller or the spring configuration file.

我还需要做什么才能使验证生效?我是否对控制器或弹簧配置文件进行了任何更改。

<mvc:annotation-driven />

<context:component-scan base-package="com.myapp" />

<mvc:resources location="/resources/" mapping="/resources/**" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass">
        <value>org.springframework.web.servlet.view.tiles2.TilesView</value>
    </property>
</bean>

<bean id="tilesConfigurer"
    class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/tiles.xml</value>
        </list>
    </property>
</bean>

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>com/dimex/resourceBundles/ApplicationResources</value>
            <value>com/dimex/resourceBundles/errors</value>
        </list>
    </property>            
  </bean>

<mvc:interceptors>  
    <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="locale"></property>
    </bean>
</mvc:interceptors>

<bean id="localeResolver"
    class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

EDIT:-

编辑:-

Do I need to have hibernate validator in my classpath. We are not using hibernate in our application. Please help.

我的类路径中是否需要有休眠验证器。我们没有在我们的应用程序中使用休眠。请帮忙。

EDIT2:-

编辑2:-

When I use validation annotations (@NotNull, @Size etc) directly in my entity class then @Valid annotations in controller works but if I remove them from my entities and try to use the validator written above then @Valid does not work.

当我直接在我的实体类中使用验证注释(@NotNull、@Size 等)时,控制器中的 @Valid 注释有效,但如果我从实体中删除它们并尝试使用上面编写的验证器,则 @Valid 不起作用。

Is it like that @Valid annotations only work with the validation annotation in the entities only and not with the validators? In order to use my validators will I have to invoke the validate method in my validator directly?

@Valid 注释是否仅适用于实体中的验证注释,而不适用于验证器?为了使用我的验证器,我是否必须直接在我的验证器中调用验证方法?

回答by Raghuram

From what I understand you are trying to combine JSR-303@Valid annotation with classic spring validation. Why would you want to do this? The equivalent JSR-303 annotations for UserValidatorclass would be something like below:

据我了解,您正在尝试将JSR-303@Valid 注释与经典的 spring 验证结合起来。你为什么想做这个?类的等效 JSR-303 注释UserValidator如下所示:

@NotNull
@Size(min=1)
private String userName;

@NotNull
@Size(min=1)
private String password

...

The spring documentationillustrates the steps needed to configure JSR-303 validation. You would need hibernate-validator(or another JSR-303 provider) for the above to work. You would also need to configure the validatorbean as below.

spring文档说明了配置 JSR-303 验证所需的步骤。您需要hibernate-validator(或其他 JSR-303 提供者)才能使上述工作正常进行。您还需要validator如下配置bean。

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

The other answers to this question are in the same line as well.

这个问题的其他答案也在同一条线上。

回答by Dave

You need to define the validator to use in your controller using the @InitBinder annotation, for example:

您需要使用 @InitBinder 批注定义要在控制器中使用的验证器,例如:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(new UserValidator());
}

回答by gskillz

Other way around is to call spring validator initialization from your controller

另一种方法是从您的控制器调用 spring 验证器初始化

DataBinder dataBinder = new DataBinder(user);
dataBinder.setValidator(userValidator);
dataBinder.validate();

BindingResult result = dataBinder.getBindingResult();

if(result.hasErrors() == false) {
   // error exists
} 

回答by user3591738

You need to put @Componenton the Validatorimplementation so that Spring container can recognize it as:

你需要把@ComponentValidator,使Spring容器可以将其识别为实现:

@Component
public class UserValidator implements Validator {

and use following method in the controller:

并在控制器中使用以下方法:

@InitBinder(UserVO) protected void initBinder(WebDataBinder binder) { binder.setValidator(userValidator); }

@InitBinder(UserVO) protected void initBinder(WebDataBinder binder) { binder.setValidator(userValidator); }

回答by schiavuzzi

If you use JSR-303-style validation with Spring (i.e. a global Validator instance provided by a JSR-303 implementation, such as Hibernate Validator), andyou have an @InitBinder-annotated method in your Controller, you mustinject the Validatorinto your Controller andset it in the @InitBindermethod:

如果您使用JSR-303风格的验证与春季(即由JSR-303实现,如Hibernate验证提供了一个全球性的验证实例),你有一个@InitBinder在你的-annotated方法Controller,你必须注入Validator到你的控制器集它在@InitBinder方法中:

@Autowired
public void setValidator(Validator validator) {
    this.validator = validator;
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(this.validator);
}

The WebDataBinder's validator is by default set to null, not (as you would expect) to the global JSR-303 Validator instance, so your models won't be validated by Spring unless you set the Validator instancemanually here.

WebDataBinder的验证是默认设置为null,并非(如你所期望的)全球JSR-303的校验器实例,所以你的车型将不会被春天验证,除非您设置的验证实例手动这里。

This is only if you have an @InitBindermethod. If you don't, everything works as expected.

只有当你有一个@InitBinder方法时才会这样做。如果不这样做,一切都会按预期进行。