Forms SpringMVC为验证失败的表单POST返回HTTP状态

Forms SpringMVC为验证失败的表单POST返回HTTP状态,forms,validation,spring-mvc,http-status-codes,Forms,Validation,Spring Mvc,Http Status Codes,如果您有一个用于HTML表单的Spring MVC@Controller,并且 您为表单的命令对象提供了一个验证器 一个表单将使用该验证器发布未通过验证的值 因此,将BindingResult提供给请求处理程序hasErrors() 请求处理程序返回表单视图名称作为要使用的视图名称,因此用户可以看到错误消息并提交更正的表单 回复客户端的HTTP状态代码是什么?是吗,就像我们可能的那样?也就是说,Spring是否检查BindingResult,并使用是否存在错误来设置状态代码 示例代码: @C

如果您有一个用于HTML表单的Spring MVC
@Controller
,并且

  • 您为表单的命令对象提供了一个
    验证器
  • 一个表单将使用该验证器发布未通过验证的值
  • 因此,将
    BindingResult
    提供给请求处理程序
    hasErrors()
  • 请求处理程序返回表单视图名称作为要使用的视图名称,因此用户可以看到错误消息并提交更正的表单
  • 回复客户端的HTTP状态代码是什么?是吗,就像我们可能的那样?也就是说,Spring是否检查
    BindingResult
    ,并使用是否存在错误来设置状态代码


    示例代码:

     @Controller
     public class MyController {
    
        public static class Command {
           ...
        }
    
        public static final String COMMAND = "command";
        public static final String FORM_VIEW = "view";
    
        private Validator formValidator = ...
    
        @RequestMapping(value = { "myform" }, method = RequestMethod.POST)
        public String processAddCheckForm(
           @ModelAttribute(value = COMMAND) @Valid final Command command,
           final BindingResult bindingResult) {
           if (!bindingResult.hasErrors()) {
              // Do processing of valid form
              return "redirect:"+uri;
           } else {
              return FORM_VIEW;
              // What status code does Spring set after this return?
           }
        }
    
        @InitBinder(value = COMMAND)
        protected void initAddCheck(WebDataBinder binder) {
           binder.addValidators(formValidator);
        }
     }
    

    可能令人惊讶的是,状态代码不是400(错误请求),而是200(正常)


    这大概是为了确保用户的web浏览器将显示带有错误消息的表单,而不是一般的400(错误请求)错误页面。但是,如果您的请求处理程序在这种情况下将状态代码设置为400,Firefox看起来还可以。

    如果使用例如ajax调用spring mvc控制器,并且验证失败后需要状态400,则可以使用ModelAndView。 ModelAndView允许更改响应的状态代码:

    if (bindingResult.hasErrors()) { 
    ModelAndView modelAndView = new ModelAndView("template", "entity", entity);
    modelAndView.setStatus(HttpStatus.BAD_REQUEST);
    return modelAndView; 
    }
    

    我在回答我自己的问题。