400 Hibernate @Valid的错误请求

时间:2014-04-21 17:52:04

标签: spring hibernate validation tomcat hibernate-validator

当我验证表单时,我有一种奇怪的行为。

一旦我添加了Hibernate @Valid注释,如果发布的数据无效,Tomcat会将我的请求视为“不好”。如果数据有效,不用担心。

我用:

  • Tomcat 7.0.52
  • Javax Validation api 1.1.0.Final
  • Hibernate Validator 5.1.0.Final
  • Spring 4.0.3.RELEASE

目前,我做了一个非常简单的验证:

public class RemoveCacheElementForm {

    @NotBlank(message = "Please select a cache name.")
    private String name;

    @NotBlank(message = "Please select a cache entry key.")
    private String key;

Spring控制器:

/**
 * Handler to remove one cached elements from the specified cache.
 * 
 * @return the view.
 */
@RequestMapping(value = CACHE_REMOVE, method = RequestMethod.POST)
public String removeCachedElement(ModelMap model, @Valid @ModelAttribute(FORM_NAME) RemoveCacheElementForm form) {
    model.addAttribute("removeElementResult", CacheUtils.removeCachedElement(form.getName(), form.getKey()));
    initializeModel(model);
    return CACHE_ADMIN_PAGE;
}

当我删除@Valid注释时,不用担心。

有人有想法吗?

非常感谢你的帮助! : - )

1 个答案:

答案 0 :(得分:9)

尝试将代码更改为

@RequestMapping(value = CACHE_REMOVE, method = RequestMethod.POST)
public String removeCachedElement(ModelMap model, @Valid @ModelAttribute(FORM_NAME) RemoveCacheElementForm form, BindingResult bindingResult) {
    model.addAttribute("removeElementResult", CacheUtils.removeCachedElement(form.getName(), form.getKey()));
    initializeModel(model);
    return CACHE_ADMIN_PAGE;
}