springboot 訪問jar同級別下的文件訪問問題


最近使用springboot打包上傳的時候遇到一個問題,就是訪問與jar同級別的文件,之前使用最多的是war形式,所以很好設置靜態資源路徑。

但是jar是看不到里面的文件夾的,所以把文件上傳到與jar同級別的upload下,這樣就需要在項目中設置upload也應該是靜態資源。

 

關鍵代碼

//靜態資源配置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //需要配置1:--- 需要告知系統,這是要被當成靜態文件的!  設置內部靜態資源
        //第一個方法設置訪問路徑前綴,第二個方法設置資源路徑
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/upload/**").addResourceLocations("classpath:/upload/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
     //關鍵在這
        //  獲取與jar同級目錄下的upload文件夾  設置與jar同級靜態資源配置
        ApplicationHome h = new ApplicationHome(this.getClass());
        // 本地獲取的路徑 D:\idea\springboot2.x\target  upload 跟 項目jar平級
        String path = h.getSource().getParent();
        String realPath = path + "/upload/";
        registry.addResourceHandler("/upload/**").addResourceLocations("file:"+realPath);
    }

設置好之后,還遇到了一個問題,css,js加載不了,因為我使用的是nginx處理的靜態資源,也要將這些進行代理,代碼如下

server {
  listen 80;
  server_name springboot.kingsuper.net;
  access_log /data/wwwlogs/springboot.kingsuper.net_nginx.log combined;
  index index.html index.htm index.jsp;
  root /data/wwwroot/springboot.kingsuper.net;
  
  #error_page 404 /404.html;
  #error_page 502 /502.html;
  
  location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
    proxy_pass http://127.0.0.1:8080;
    expires 30d;
    access_log off;
  }

  location ~ .*\.(js|css)?$ {
    proxy_pass http://127.0.0.1:8080;
    expires 7d;
    access_log off;
  }

  location ~ /\.ht {
    deny all;
  }
  
  location ~ {
    proxy_pass http://127.0.0.1:8080;
    include proxy.conf;
  }
}

設置好之后,就可以訪問了,over

 


免責聲明!

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



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