【问题标题】:Spring MVC: how to handle incoming request to wrong context pathSpring MVC:如何处理对错误上下文路径的传入请求
【发布时间】:2017-09-24 00:25:55
【问题描述】:

我们如何处理 spring mvc 中对错误上下文路径的传入请求?

我已经部署了一个 spring mvc 应用程序,其 contextpath 为

http://exampledomain.com/mycontext

但是当我尝试访问 url http://exampledomain.com/wrongcontext 时,我收到错误为 HTTP 状态 404 - /wrongcontext/

我已经实现了错误处理,当使用正确的上下文路径时,它适用于所有错误的 url,但不适用于错误的上下文路径。

我正在尝试了解我们如何将所有传入请求重定向到生产环境中的特定页面..

提前致谢

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    您的应用程序只能看到对其上下文的请求/mycontext 对于其他上下文的请求,您的应用程序无能为力。

    但是,您可以在根上下文 / 部署应用程序并在那里实现错误处理程序。

    看看这个答案:How to customize JBoss AS7 404 page

    这个答案与 JBoss 有关,但同样的想法也适用于其他服务器。

    【讨论】:

      【解决方案2】:

      在 Spring 中无法处理错误的上下文路径请求,因为它只会处理到达上下文根的请求。您必须查看服务器配置参数以重定向此类请求。如果您正在使用 Tomcat,请检查 context.xml 的 path 参数: https://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context

      【讨论】:

        【解决方案3】:

        我们可以在@Controller@ControllerAdvice 中使用@ExceptionHandler 来处理此类异常并决定要呈现的视图页面。

        @ExceptionHandler({ HttpRequestMethodNotSupportedException.class,
                HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class,
                MissingPathVariableException.class, MissingServletRequestParameterException.class,
                ServletRequestBindingException.class,MethodArgumentNotValidException.class, MissingServletRequestPartException.class, 
                NoHandlerFoundException.class})
            public ModelAndView handleException(){
                return new ModelAndView("errorpage");
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-09-24
          • 2015-07-11
          • 2017-04-02
          • 1970-01-01
          • 1970-01-01
          • 2015-04-05
          • 2015-04-28
          相关资源
          最近更新 更多