【问题标题】:400 Bad request when validation Model Attribute with Spring MVC使用 Spring MVC 验证模型属性时出现 400 错误请求
【发布时间】:2015-07-04 20:41:28
【问题描述】:

我正在编写一个接受用户注册请求的简单控制器我想验证模型属性,但收到 400 错误请求。 我检查了this question here,这几乎是我遇到的问题,但解决方案对我不起作用。

 @RequestMapping(method = RequestMethod.POST, value = "/sign-up", consumes = "application/x-www-form-urlencoded")
    public ModelAndView addUser(ModelMap model,@Valid @ModelAttribute
    UserRegistrationInfo userRegistrationInfo,
                                HttpServletRequest httpRequest,
                                HttpSession httpSession,
                                BindingResult result) { ..... } 

编辑

春季版:4.0.6.RELEASE

看过SpringMVC架构,在DefaultHandlerExceptionResolverclass,doResolveException方法处设置断点,发现抛出了BindException异常。但是不知道为什么BindingResult没有填充,没有调用方法执行让我确定我想要什么行为?执行以返回 handleBindException((BindException) ex, request, response, handler); 结束,即

protected ModelAndView handleBindException(BindException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return new ModelAndView(); } 

【问题讨论】:

  • 请附上堆栈跟踪或日志!!
  • 嗯,这是我第一次尝试看,但到目前为止没有任何可疑之处
  • 没有日志到目前为止我找不到任何东西......它在没有任何日志的情况下优雅地返回
  • UserRegistrationInfo 是什么样的?它有无参数构造函数吗?
  • 是的,它实际上有一个setter和getter

标签: spring validation spring-mvc


【解决方案1】:

正如您正确理解的那样,由于绑定错误,您收到了错误的请求。您需要的所有信息实际上都包含在 BindingResult 对象中,但为了正确使用它,您应该将您的 BindingResult 设置为立即跟随您的 ModelAttribute 例如

 @RequestMapping(method = RequestMethod.POST, value = "/sign-up", consumes = "application/x-www-form-urlencoded")
    public ModelAndView addUser(ModelMap model,@Valid @ModelAttribute
    UserRegistrationInfo userRegistrationInfo, BindingResult result
                                HttpServletRequest httpRequest,
                                HttpSession httpSession,
                                ) { ..... }

虽然参数的顺序通常无关紧要,但BindingResult 参数是一个例外,因为该方法可以包含多个ModelAttribute 参数,每个参数都有自己的BindingResult 专用实例。在这种情况下,通过将BindingResult 参数紧跟在它适用的ModelAttribute 之后来建立关联。

当您重新排序参数时,您将不再收到 400 错误,而是请求将进入控制器,并且日志将显示确切的绑定问题,或者您只需检查 result.hasErrors() 并遍历字段错误致电result.getAllErrors()。那么它应该足够简单来解决您的绑定问题以及随之而来的错误请求。

查看文档http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-methods的部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2015-08-18
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多