springmvc 使用jsr303校驗返回400錯誤

如果一個方法中有參數被 @Valid 標註了,但該參數後面沒有緊跟一個 BindingResult 類型的參數,那麼提交到該方法時,將返回 400 錯誤。
錯誤消息將會是:The request sent by the client was syntactically incorrect ().

錯誤的方法定義 1 :(錯誤原因:沒有 BindingResult 參數)

@RequestMapping({"error400" })
public String error400(@Valid @ModelAttribute("testForm") TestForm testForm) {
return"test";
}
錯誤的方法定義 2 :(錯誤原因:沒有緊跟在 @Valid 參數之後)

@RequestMapping({"error400" })
public String error400(@Valid @ModelAttribute("testForm") TestForm testForm, Model model, Errors result) {
return"demo/front/test";
}
也可參考 DefaultHandlerExceptionResolver.java 中的方法說明:

/**
* Handle the case where an {@linkplain ModelAttribute @ModelAttribute} method
* argument has binding or validation errors and is not followed by another
* method argument of type {@link BindingResult}.
* By default an HTTP 400 error is sent back to the client.
* @param request current HTTP request
* @param response current HTTP response
* @param handler the executed handler
* @return an empty ModelAndView indicating the exception was handled
* @throws IOException potentially thrown from response.sendError()
*/
protectedModelAndView handleBindException(BindException ex, HttpServletRequest request,
HttpServletResponse response, Object handler)throws IOException {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
returnnew ModelAndView();
}

轉自:http://blog.csdn.net/lougnib/article/details/9973257
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章