簡體   English   中英

使用Servlet上下文從Spring Boot應用程序獲取資源的路徑

[英]Get the Path of a resource from a spring boot aplication using servlet context

我有這個結構,由spring boot生成

在此處輸入圖片說明

所以我想使用sevletContext獲得文件gastos.xlsx的輸入流。

    @Autowired
    private ServletContext context;

    @GetMapping("/grafico")
    public ResponseEntity<String> exportExcelGrafico(HttpServletResponse response){

        try{
               //this path returns null. What is the real path to put here? 
             InputStream input = context.getResourceAsStream("src/main/resources/templates/gastos.xlsx");
             //returns null
             input = context.getResourceAsStream("/resources/templates/gastos.xlsx");
             // Returns null
             input = context.getResourceAsStream("/templates/gastos.xlsx");
        }
        catch(){

        }

正確的道路是什么? 我沒有在application.properties上配置任何內容

Maven或Gradle項目的src/main/resources文件夾中的內容最終出現在jar中,而不是Web資源中。 因此,應該使用類加載器而不是servlet上下文來加載它:

MyClass.class.getResourceAsStream("/templates/gastos.xlsx")

不確定為什么將文件放在模板下,因為...這不是模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM