Spring4 表单验证

Spring4 Form Validation

我遇到的情况与下面类似:

public class Shop {
  @NotNull
  String name;
  @NotNull
  String desc;
}

用于显示我必须插入用户的表单的按钮:

<form:form method="post" action="saveShop.html" modelAttribute="Shop">

<form:label path="name">Name:</form:label>
<form:input path="name" value="${shop.name}" />
<form:label path="desc">desc:</form:label>
<form:input path="desc" value="${shop.desc}" />
<input type="submit" value="Submit"/>
</form:form>

控制器:

@RequestMapping("/addShop")
public ModelAndView LoadFormPage(@ModelAttribute("Shop")Shop shop) {
    ModelAndView model = new ModelAndView();
    model.setViewName("/shop/addShop");
    return model;
}

@RequestMapping(value = "/saveShop", method = RequestMethod.POST)  
public ModelAndView saveShop(@Valid @ModelAttribute("Shop") Shop shop, BindingResult result) {
    if (result.hasErrors()) { *do some*
    } else { *do someelse* }
}

即使我将所有字段留空(我什至尝试过使用不同的数据类型)并提交表单,控制器也不会识别错误。

你能帮帮我吗?

确保添加以下配置。

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

<mvc:annotation-driven validator="myBeansValidator">

<!-- Hibernate Validator -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.2.0.Final</version>
</dependency>

改编自Spring MVC form validation not working