开发者

Spring 3 validation not working

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.

public class UserValidator implements Validator {

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

public void valid开发者_如何学Goate(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:-

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.

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?


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 UserValidator class would be something like below:

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

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

...

The spring documentation illustrates 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 validator bean as below.

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

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


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

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


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

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

BindingResult result = dataBinder.getBindingResult();

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


You need to put @Component on the Validator implementation so that Spring container can recognize it as:

@Component
public class UserValidator implements Validator {

and use following method in the controller:

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


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), and you have an @InitBinder-annotated method in your Controller, you must inject the Validator into your Controller and set it in the @InitBinder method:

@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 instance manually here.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜