Spring表单ModelAttribute字段验证避免400 Bad Request错误

2024-05-17

我有一个ArticleFormModel包含正常发送的数据html form由 Spring 使用注入@ModelAttribute注释,即

@RequestMapping(value="edit", method=RequestMethod.POST)
public ModelAndView acceptEdit(@ModelAttribute ArticleFormModel model, 
    HttpServletRequest request, BindingResult errors)
{
    //irrelevant stuff
}

在某种程度上,一切都运行得很好。问题是ArticleFormModel包含一个double field (protected,使用普通设置器设置)。只要用户发送的数据是数字,一切就可以正常工作。当他们输入一个单词时,我得到的只是400 Bad Request Http Error.

我已经注册了一个WebDataBinder对于该控制器

@InitBinder
protected void initBinder(WebDataBinder binder) throws ServletException
{
    binder.setValidator(validator);
}

where validator是一个自定义类的实例,实现org.springframework.validation.Validator界面 但我不知道下一步该做什么。我希望能够解析模型、获取有效的 HTTP 响应并在表单中显示错误消息。这initBinder()方法被调用,我可以调用validator.validate()但它不会改变错误(对于错误的数据)。

我知道我可以使用设置器来解析字符串,检查它是否是数字,如果不是,则将该信息存储在变量中,然后在验证期间检索该变量,但这似乎工作量太大。必须有一种更简单的方法来在字段上强制输入类型而不会出现错误。另外,问题在于数据绑定,而不是验证,所以我觉得它应该放在相应的代码层中。

我也在考虑实施java.beans.PropertyEditor并打电话binder.registerCustomEditor(),但我缺乏可靠的知识来源。

客户端验证(通过 JavaScript 检查数据是否为数字)是不可能的。

TL;DR:

如何强制字段为特定类型@ModelAttribute没有得到的物品400 Bad Request Http Error?


您可以使用<form:errors>对于绑定错误。

它看起来像这样:

控制器:

@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参数需要放在模型后面的右边。

详细信息请参见下文(示例 17.1):

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-methods 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>

消息属性文件:

typeMismatch.articleFormModel.price=customized error message
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring表单ModelAttribute字段验证避免400 Bad Request错误 的相关文章

随机推荐