Spring form ModelAttribute field validation to avoid 400 Bad Request Error

巧了我就是萌 提交于 2019-12-03 14:42:23

You can use <form:errors> for a binding error.

It looks like this:

Controller:

@RequestMapping(value="edit", method=RequestMethod.POST)
public ModelAndView acceptEdit(@ModelAttribute ArticleFormModel model, 
    BindingResult errors, HttpServletRequest request)
{
  if (errors.hasErrors()) {
    // error handling code goes here.
  }
  ...
}

errors parameter is needed to be placed on the right after the model.

See below for details (Example 17.1):

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-methods

jsp:

<form:form modelAttribute="articleFormModel" ... >
  ...
  <form:errors path="price" />
</form:form>

message properties file:

typeMismatch.articleFormModel.price=customized error message
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!