请求处理失败;嵌套异常是javax.validation.ConstraintViolationException:类

时间:2017-07-31 08:39:49

标签: java validation spring-mvc spring-validator nhibernate-validator

我收到了以下验证异常。我在之前的同一个问题上探讨了一些答案,但对我来说没有任何作用。

  

org.springframework.web.util.NestedServletException:Request   处理失败;嵌套异常是   javax.validation.ConstraintViolationException:验证失败   在组的持续时间内,类[com.rg.spring.model.User]   [javax.validation.groups.Default,]       违反约束的清单:[         ConstraintViolationImpl {interpolatedMessage ='可能不为空',propertyPath = fname,rootBeanClass = class com.rg.spring.model.User,   messageTemplate = '{} org.hibernate.validator.constraints.NotEmpty.message'}       ]         org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)         org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)

在我的模特中我有

@NotEmpty
@Column(name = "fname", nullable = false)
String fname;

我有控制器

@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "registration";
        }
        service.saveUser(user);
        model.addAttribute("success", "User " + user.getFname() + " registered successfully");
        return "success";
    }

我有以下messages.properties

NotEmpty.user.fname = First Name is required!

在pom中添加了依赖关系

<!-- jsr303 validation -->
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.3.Final</version>
</dependency>

以下是UI表单

<form:form method="POST" modelAttribute="user">
    <form:input type="hidden" path="id" id="id"/>
    <table>
        <tr>
            <td><label for="fname">First Name: </label> </td>
            <td><form:input path="fname" id="fname"/></td>
            <td><form:errors path="fname" cssClass="error"/></td>
        </tr>

我有以下方法在AppConfig

下加载消息
@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    return messageSource;
}

1 个答案:

答案 0 :(得分:0)

控制器类:

@RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveUser(@Valid @ModelAttribute("user") User user, BindingResult result,
        ModelMap model) {

    if (result.hasErrors()) {
        return "registration";
    }
    service.saveUser(user);
    model.addAttribute("success", "User " + user.getFname() + " registered successfully");
    return "success";
}

在控制器类中添加此方法。此方法删除空格。

@InitBinder
public void InitBinder(WebDataBinder dataBinder) {
    StringTrimmerEditor stringTrimmerEditor = new StringTrimmerEditor(true);
    dataBinder.registerCustomEditor(String.class, stringTrimmerEditor);
}

我希望,这会奏效。