首页 > 解决方案 > Spring Boot 中的 HTTP 响应过滤器

问题描述

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

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

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

我想建立类似的东西:

有一些方法:在课堂上处理它InterceptorFilter课堂上,也@ControllerAdvice做一些我想要的(我建造的)。

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

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

标签: spring-boothttptomcat9

解决方案


试试这个方法

@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");
}
}

推荐阅读