Hibernate Validator不起作用,但我不知道为什么

时间:2018-06-28 05:35:14

标签: java spring-mvc hibernate-validator

我在模型类上添加了一些约束注释:

public class Items {
    private Integer id;

    @Size(min=1,max=30,message="${items.name.length.error}")
    private String name;

    private Float price;

    @NotNull(message="${items.createTime.isNUll}")
    private Date createTime;

    // setters and getter 
}

public class ItemsCustom extends Items {

    // add some new details

}

我还设置了配置XML文件:

<mvc:annotation-driven
    conversion-service="conversionService" validator="validator"></mvc:annotation-driven>

<bean id="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="providerClass"
        value="org.hibernate.validator.HibernateValidator" />
    <property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>classpath:CustomValidationMessages</value>
        </list>
    </property>
    <property name="fileEncodings" value="utf-8" />
    <property name="cacheSeconds" value="120" />
</bean>

这是CustomValidationMessages.properties:

items.name.length.error=the length of name must be more than 1 character and less than 30 characters 
items.createTime.isNUll=the create time must be not null

这是控制器:

@RequestMapping(value="/submitItems",method=RequestMethod.POST)
public ModelAndView submitItems(@Validated ItemsCustom itemsCustom,BindingResult bindingResult) throws Exception{

    List<ObjectError> errors = bindingResult.getAllErrors(); 
    if(bindingResult.hasErrors()) {
        System.out.println();
        for(ObjectError e : errors) {
            System.out.println(e.getDefaultMessage());
        }
    }

    ModelAndView mav = new ModelAndView();
    // some process...
    return mav;
}

我认为一切就绪,但是没有用!有人帮忙吗?

1 个答案:

答案 0 :(得分:1)

将控制器@Validated中的注释更改为@Valid

import javax.validation.Valid;