【问题标题】:HTTP Response Filter in Spring BootSpring Boot 中的 HTTP 响应过滤器
【发布时间】:2019-02-22 06:26:57
【问题描述】:

我有一个类似http://example.com 的网站,并且我的网站下有很多 URL(http://example.com/a、/ab、/abc 等)。

同时假设spring boot项目中我的资源文件下有很多视图文件(x.html、y.html等)。

我将它部署在 Centos 服务器的 Tomcat9 中。

我想构建类似的东西:

  • if (HTTPResponse!=200) -> 路由到 x.html(请求的所有响应传入我项目中的所有 URL)
  • else -> 处理正常的 HTTP 请求响应流

有一些方法:在Interceptor 类、Filter 类中处理它,也可以在@ControllerAdvice 中制作一些我想要的东西(我建造)。

所以我不想在我的网站上显示 HTTP 错误。如果出现 HTTP 错误,请将其路由到我的 x.hmtl 页面,否则处理常规的 Req-Resp 流。

构建它的最佳方法是什么?你有什么建议?

【问题讨论】:

    标签: spring-boot http tomcat9


    【解决方案1】:

    试试这个方法,

    @ControllerAdvice
    public class ExceptionController {
    @ExceptionHandler(Exception.class)
    public ModelAndView handleError(HttpServletRequest request, Exception e)   {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
        return new ModelAndView("error");
    }
    
    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleError404(HttpServletRequest request, Exception e)   
    {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
        return new ModelAndView("404");
    }
    }
    

    【讨论】:

    • 我知道这种方式。但是如果 HTTP 响应状态为 400(错误请求),我们无法捕获并路由到页面。谢谢
    猜你喜欢
    • 2017-06-09
    • 2020-08-11
    • 2016-06-17
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2015-05-26
    • 2015-05-22
    相关资源
    最近更新 更多