Проверка Spring Web MVC с помощью Hibernate Validator не отображает ошибки в BindingResult

I've been using Hibernate Validator in my Spring project. I'm about to validate my JUser Object automatically. i.e, I want Spring to validate the Object and set errors in BindigResult. But It doesn't work.

pom.xml

<properties>
    <spring.version>4.3.5.RELEASE</spring.version>
    <spring.security.version>4.0.2.RELEASE</spring.security.version>
    <hibernate.version>4.3.11.Final</hibernate.version>
    <validation-api.version>1.1.0.Final</validation-api.version>
    <hibernate-validator.version>5.4.0.Final</hibernate-validator.version>
</properties>
....

applicationContext.xml

...
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<context:annotation-config />
<context:component-scan base-package="my.project.controller" />
<mvc:annotation-driven validator="validator">
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages"/>
</bean>

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean>
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
    <property name="validator" ref="validator"/>
</bean>
<bean id="localeResolver"
      class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en" />
</bean>

JUser.java

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;

@Entity
public class JUser implements Officeable {

   @Id
   private Long id;

   @Column(unique = true, nullable = false)
   private String username;

   private String password;

   @NotEmpty
   private String firstName;

   @NotEmpty
   private String lastName;
   private String tel;
}

UserController.java

import javax.validation.ConstraintViolationException;
....

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update2(HttpServletRequest request, Model model, @ModelAttribute("user") @Valid JUser user, BindingResult result) {
    if (!result.hasErrors()) {
        System.out.println("binding result has no errors for user ");
        try {
            JUser updated = userService.update(user);
            model.addAttribute("user", updated);
        } catch (MessageException | DataIntegrityViolationException ex) {
            result.reject("user", ex.getMessage());
        } catch (ConstraintViolationException cvex) {
            for (ConstraintViolation cv : cvex.getConstraintViolations()) {
                result.rejectValue(cv.getPropertyPath().toString(),cv.getMessageTemplate() , cv.getMessage());
            }
        }
    }
    return "user/manage";
}

As you see in the above controller method I want Spring to validate the user Object and set errors in BindigResult. But It does not work.
For example when user has empty firstName I face the output:

output:
binding result has no errors for user 

and I have to catch hibernate thrown exceptions by hand:

 ConstraintViolationException: may not be empty ...

more description. I've used String @Validated annotation and It did not work as well. I've read more than ten related stackoverflow questions and they didn't solved my problem.

7 голосов | спросил Dariush Jafari 8 MaramWed, 08 Mar 2017 00:07:07 +03002017-03-08T00:07:07+03:0012 2017, 00:07:07

0 ответов


Похожие вопросы

Популярные теги

security × 330linux × 316macos × 2827 × 268performance × 244command-line × 241sql-server × 235joomla-3.x × 222java × 189c++ × 186windows × 180cisco × 168bash × 158c# × 142gmail × 139arduino-uno × 139javascript × 134ssh × 133seo × 132mysql × 132