2014-09-25 118 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; 
} 
}