2014-09-25 72 views
0

好吧我正在使用Spring MVC 4.0,並且在從Controller讀取txt文件時遇到問題。Spring MVC如何從控制器訪問靜態資源

我在調度員的servlet

<mvc:resources mapping="/docs/**" location="/docs/"/> 

所以定在我的文檔設置file.txt,我想讀從控制器文件。

@RequestMapping("/file") 
public class FileController { 

    @RequestMapping(method=RequestMethod.GET) 
    public String getFile() throws IOException{ 
     BufferedReader br = new BufferedReader(new FileReader("docs/file.txt")); 
     StringBuilder sb = new StringBuilder(); 
     try { 

     String line = br.readLine(); 
     while (line != null) { 
      sb.append(line); 
      line = br.readLine(); 
     } 
     } finally { 
      br.close(); 
     } 
     return sb.toString(); 
    } 

} 

我曾嘗試的FileReader(路徑)所有的路徑,我不能讓這個文件......我該怎麼辦呢?

我的目錄結構是:

Application 
---WepPages 
-------META-INF 
-------WEB-INF 
-------docs 

---SourcePackages 
---Libraries 
. 
. 
. 
. 
. 
+1

你在混合「資源」的定義。靜態資源由Spring MVC自動處理,不需要專用控制器。 – chrylis 2014-09-25 21:17:30

回答

0

的資源通常被包裝戰爭。這就是爲什麼你無法在文件系統中找到它們的原因。雖然你可以使用的類加載器仍然能夠訪問他們:

getClass().getResourceAsStream("/docs/file.txt") 
0

Spring可以通過使用Resource接口訪問底層資源:

@Value("file:/docs/file.txt") 
private Resource myFile; 

@RequestMapping(method = RequestMethod.GET) 
public String getFile() throws IOException { 

BufferedReader br = new BufferedReader(new FileReader(myFile.getFile())); 
    // do something 
} 
0

您可以使用ServletContext讀取文件。例如

ServletContext context = //... 
InputStream is = context.getResourceAsStream("/docs/file.txt"); 

此外,請檢查 - ServletContext and Spring MVC

0

我需要這樣做來爲我的視圖聚合js和css文件的列表。
可以將文件路徑傳遞給視圖,以便它們不需要手動註冊。
這就是我所做的 -

@Controller 
public class HomeController { 

WebApplicationContext webappContext; 

List<String> jsFiles = new ArrayList<>(); 
List<String> cssFiles = new ArrayList<>(); 

@Autowired 
public HomeController(ServletContext servletContext) throws IOException{ 

    webappContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); 


    Resource[] jsResources = webappContext.getResources("content/modules/**/*.js"); 
    Resource[] cssResources = webappContext.getResources("content/modules/**/*.css"); 

    for (Resource resource : jsResources) { 
     jsFiles.add(resource.getURL().getPath()); 
    } 
    for (Resource resource : cssResources) { 
     cssFiles.add(resource.getURL().getPath()); 
    } 
} 
@RequestMapping({ "/", "/home**" }) 
public ModelAndView getHomePage() { 

    ModelAndView modelAndView = new ModelAndView(); 

    modelAndView.setViewName("home"); 
    modelAndView.addObject("jsFiles", jsFiles); 
    modelAndView.addObject("cssFiles", cssFiles); 

    return modelAndView; 
} 
}