繁体   English   中英

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

[英]Available options in Spring MVC to customise the 405 error response?

请指导我。

停留在与Spring MVC有关的2个问题上-

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

{“ cause”:null,“ stackTrace”:[{“ methodName”:“ resolveHandlerMethod”,“ fileName”:“ AnnotationMethodHandlerAdapter.java”,“ lineNumber”:123,“ className”:“ org.springframework.web.servlet。 mvc.annotation.AnnotationMethodHandlerAdapter $ ServletHandlerMethodResolver“,” nativeMethod“:false},...

我尝试通过各种建议来消除此问题,例如@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

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

有什么建议吗?

  1. 其次,我试图扩展

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

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

我们不能修改这种行为吗?

您可以这样做来扩展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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM