Resource interpreted as Stylesheet but transferred with MIME type text/html 解決方式

前提

此解決方法適用於因全局過濾器導致的問題


問題介紹

問題效果是:
CSS文件訪問到,但是HTML本身沒有加載樣式,並且瀏覽器控制檯輸出Resource interpreted as Stylesheet but transferred with MIME type text/html的字樣


問題原因

使用Servlet時,由於需要每次給request和response設置編碼格式,從而使用了一個全局的過濾器,將每次的請求的數據變爲 text/html 導致CSS文件無法解析。
類似於下面的代碼情況

//xml配置
<filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>
//java配置
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //        設置請求編碼格式
        req.setCharacterEncoding("utf-8");  //post 改變(請求實體)
        //        設置響應編碼格式
        resp.setContentType("text/html;charset=utf-8");
        chain.doFilter(req, resp);
    }

解決

增加一個專門解析css文件的過濾器,並將響應格式改爲 text/css即可

//新xml配置
<filter-mapping>
        <filter-name>FilterCss</filter-name>
        <url-pattern>*.css</url-pattern>
</filter-mapping>
//新java配置
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //        設置請求編碼格式
        req.setCharacterEncoding("utf-8");  //post 改變(請求實體)
        //        設置響應編碼格式
       resp.setContentType("text/css;charset=utf-8");//修改響應編碼
        chain.doFilter(req, resp);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章