4

我对 Spring MVC 中的数据绑定有疑问。

我有一个控制器,它接受 @RequestBody 形式的 JSON 请求。我有所有的 JSR 303 验证,它就像一个魅力。

  • JSON 请求

    public class TestJSONRequest {
    
        @Size(min=10,message="{invalid.demo.size}")
        String demo;
    
        int code;
    }
    
  • 控制器

    @Controller
    @RequestMapping("/test")
    public class TestController {
    
        public void testEntry(@RequestBody TestJSONRequest jsonRequest,ModelMap map)
    
          Set<ConstraintViolation<TestJSONRequest>> violationList = validator.val(jsonRequest);
          ....
          ....
          TestJSONResponse response = // Do complex Logic.
          modelMap.addattribute("TestJSONResponse",response);
        }
    }
    

但是一旦传入的 JSON 数据绑定到 Request 对象,JSR 303 验证就会启动。

如果我发送输入 JSON 请求ab代码字段,绑定本身就会失败。

我该如何处理?

我想捕捉那些数据绑定错误并在我的控制器中进行某种通用错误处理。

你能帮我解决这个问题吗?

PS - 我使用的是 Spring 3.0.3

4

1 回答 1

4

According to the current Spring documentation (V3.1) :

Unlike @ModelAttribute parameters, for which a BindingResult can be used to examine the errors, @RequestBody validation errors always result in a MethodArgumentNotValidException being raised. The exception is handled in the DefaultHandlerExceptionResolver, which sends a 400 error back to the client.

Now you can to tell Spring that you'd like to handle this, by creating a new method, as follows:

@ExceptionHandler(MethodArgumentNotValidException.class)
public String handleValidation(MethodArgumentNotValidException e, ModelMap map) {
    List<ObjectError> errors = e.getBindingResult() .getAllErrors();
    // your code here...
    return "path/to/your/view";
}

Finally, have a read of the Spring docs wrt @ExceptionHandler. There's most likely some useful information there.

于 2012-07-30T23:40:02.923 回答