400 Bad request with Hibernate @Valid

2019-02-23 19:19发布

I have a strange behaviour when I validate my form.

As soon as I add the Hibernate @Valid annotation, Tomcat consided my request as "bad" if the posted data are not valid. If the data are valid, no worries.

I use:

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

At the moment, I do a really simple validation:

public class RemoveCacheElementForm {

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

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

The Spring controller:

/**
 * 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;
}

When I remove @Valid annotation, no worries too.

Anyone has an idea?

Thanks a lot for your help! :-)

1条回答
迷人小祖宗
2楼-- · 2019-02-23 20:00

Try changing your code to

@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;
}
查看更多
登录 后发表回答