Spring MVC中的可用选项可自定义405错误响应?

时间:2018-08-09 14:56:17

标签: java spring spring-mvc model-view-controller

请引导我。

坚持与Spring MVC有关的2个问题-

  1. 在我的项目中,每当发生异常时,整个堆栈跟踪就会在响应中打印出来。像这样-
  

{       “ cause”:null,       “堆栈跟踪”: [           {               “ methodName”:“ resolveHandlerMethod”,               “ fileName”:“ AnnotationMethodHandlerAdapter.java”,               “ lineNumber”:123,               “ className”:“ org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter $ ServletHandlerMethodResolver”,               “ nativeMethod”:错误           },...

我尝试通过各种建议(例如@ControllerAdvice和@Order(0)甚至在web.xml中)来消除此问题-

<error-page>
    <location>/error/GeneralError</location>
</error-page>

因此,我能够利用从控制器(如NPE等)抛出的异常,但是无法捕获与HTTP URL相关的异常(我相信这种异常发生在控制器映射之前)。

就像我的情况一样,如果用户在REST客户端中输入POST请求而不是适用的GET URL,尽管日志中报告的错误是这样的-

Aug 09, 2018 7:05:00 PM org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleHttpRequestMethodNotSupported
WARNING: Request method 'POST' not supported

web.xml中的@ControllerAdvice或错误映射仍然无法在此处捕获405错误,因为我没有机会添加我的自定义消息。

有什么建议吗?

  1. 第二次,我尝试扩展
  

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

,并将其与web.xml中的bean定义一起使用,并带有@Controller和@ExceptionHandler批注,但Spring框架只是简单地忽略了我的努力,而再次使用默认框架。

我们不能修改此行为吗?

1 个答案:

答案 0 :(得分:0)

您可以执行此操作以扩展DispatcherServlet

尝试一下:

public class GlobalRequestHandler extends DispatcherServlet{

    @Override
    protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        //handle here as per your requirement.
        super.service(request, response);
    }
}

将此bean添加到配置类中:

@Bean
DispatcherServlet dispatcherServlet() {
    return new GlobalRequestHandler();
}