如何使用@ExceptionHandler 处理绑定异常

use*_*746 3 spring spring-mvc

我的要求是使用 Spring 3.0 和 Hibernate Validator 对表单执行服务器端验证。请记住,我正在使用 AJAX 调用提交表单。我的控制器类代码如下所示。

public ModelAndView generatePdfReport(@ModelAttribute("reports") @Valid ReportsCommand model, BindingResult result, ModelAndView modelAndView,
            HttpServletRequest request, HttpServletResponse response) throws Exception {


        if (result.hasErrors()) {

            throw new BindException(result);
        } 
        else{
           ...
           }
Run Code Online (Sandbox Code Playgroud)

更新...

   @ExceptionHandler(BindException.class)
   public @ResponseBody String handleException(BindException e,HttpServletRequest request, HttpServletResponse response) 
   {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return e.getMessage();

   }
Run Code Online (Sandbox Code Playgroud)

这是我放置在控制器中的处理程序方法。我使用了@ResponseBody 注释,但它仍然以 html 格式而不是 JSON 格式显示响应......我的代码有什么问题......下面是我的字段正在验证

@Size(min = 2, max = 3, message = "calltype must between 2 to 3 Characters.")
    private String callType;
Run Code Online (Sandbox Code Playgroud)

如果我给出的大小超过三,它就会进入 if 并抛出异常。我想要的是,我想处理这个异常并返回 json 响应。也许我可以使用 @ExceptionHandler 但不要这样做不知道如何。或者任何其他解决此问题的解决方案也将不胜感激。

小智 6

导入这个包

import org.springframework.validation.BindException
Run Code Online (Sandbox Code Playgroud)

不是这个

import java.net.BindException
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 5

没有自动将绑定错误转换为 JSON 的方法。您应该手动执行此操作。您可以在两个地方执行此操作:

  • 内联 - 而不是抛出 BindException,生成 JSON 并返回它(使用与 JSON 配合使用的自定义 ModelAndView,或通过写入响应)
  • 在声明为处理的异常处理程序中BindException。您使用@EXceptionHandler(BindException.class)和执行相同的转换错误 -> json注释某些(基本)控制器的方法,如上所述