Spring boot項目部署到Tomcat靜態資源加載失敗

1 現象

404、或者沒有加載樣式或者圖片等靜態資源
靜態資源引入失敗,在瀏覽器按住F12,看一下靜態資源路徑地址,發現
地址 : http://localhost:8080/myproject/css/my.css
疑惑:這看上去沒啥問題呀?

2 原因

原本在springboot內置Tomcat中運行項目,資源訪問路徑URL類似於:http://localhost:8080/css/my.min.css
是不是發現多了個項目名稱?
咋辦?把前臺資源路徑該一下可以嗎
http://localhost:8080 拼 /css/my.min.css
這樣可以看起來搞成功
但是如果項目使用的是Https的或者項目端口改了,是不是就跪了。有辦法解決

3 解決

使用攔截器
在Java後端定義一個攔截器,用來獲取 request.getContextPath() 然後傳到前端,request.getContextPath() 得到的是項目的根路徑
獲取的路徑是動態的,即使協議、端口號、項目名改了,靜態資源依然能找到

@Component
public class CommonIntercepter implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
         return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
         request.setAttribute("path", request.getContextPath());
    }

    @Override
    public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {

    }
}

前端 (freemarker)

<link href="${path!}/css/bootstrap.min.css" rel="stylesheet">
<link href="${path!}/css/font-awesome.min.css" rel="stylesheet">
<link href="${path!}/css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
<link href="${path!}/css/animate.css" rel="stylesheet">
<link href="${path!}/css/style.css" rel="stylesheet">

這樣在瀏覽器請求資源時候是前綴就可以動態獲取了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章