0

I have added some constraint annotations on the model class:

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

}

I have also set the configuration XML file:

<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>

And this is 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

This is the controller:

@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;
}

I think all is ready but it doesn't work! Anyone helps?

maxwellhertz
  • 473
  • 1
  • 6
  • 18

1 Answers1

1

change annotation inside controller @Validated to @Valid

import javax.validation.Valid;
Faiz Akram
  • 559
  • 4
  • 10