SpringBoot添加對靜態文件css/html/jpg等的直接訪問的支持


2019/3/2更新

使用這個方法時候如果遇到`LazyInitializationException`,請按照如下方法解決:

一、在你的項目啟動類中加入這個方法

    @Bean
    public OpenEntityManagerInViewFilter openEntityManagerInViewFilter(){
        return new OpenEntityManagerInViewFilter();
    }

 

二、在你的項目配置文件(比如:application.properties)中加入

spring.jpa.open-in-view=true

 

 ----原文----

 

解決對策

解決方法是配置WebMvcXXX(多說一句WebMvcConfigurerAdapter在Spring新版本已經過時,因此再看相應的解決方案請慎重)比如新建一個文件WebStaticResourceConfigure.java,然后碼上如下代碼:

 @Configuration
public class WebStaticResourceConfigure extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        /*
         * * 根據系統標識來判斷合適的文件路徑格式
         * * 下面將路徑中的/img/XX.jpg映射到文件系統中的D:/static/img/XX.jpg或者Unix下的/var/static/img/XX.jpg
         * * 如果需要映射的文件夾是在項目中的,比如resource/static,
         *   可以使用.addResourceLocations("classpath:/static/")
         */
        String os = System.getProperty("os.name");
        final String windowsFlag = "win";
        // windows
        if (os.toLowerCase().startsWith(windowsFlag)){  
            registry.addResourceHandler("/img/**")
                    .addResourceLocations("file:D:\\static\\img\\");
        //linux 和mac
        } else {
            registry.addResourceHandler("/img/**")
                    .addResourceLocations("file:\\var\\static\\img\\");
        }
    }
}

 

 如果沒有解決你的問題,請不要放棄,繼續在互聯網上探索了。

 

五、引用及致謝

我只是知識的搬運工,這篇文章離不開他們:

[1] https://stackoverflow.com/questions/41691770/spring-boot-unabe-to-serve-static-image-from-resource-folder

[2] https://stackoverflow.com/questions/27381781/java-spring-boot-how-to-map-my-app-root-to-index-html

[3] https://blog.csdn.net/panxiaolan/article/details/81115120

  以及其它參考過的網頁


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM