Spring MVC如何从Controller访问静态资源

时间:2014-09-25 20:52:20

标签: java spring spring-mvc

好的我正在使用Spring MVC 4.0,我在从Controller中读取txt文件时遇到问题。

我设置了我的调度程序-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
.
.
.
.
.

4 个答案:

答案 0 :(得分:1)

我需要这样做来聚合我的视图的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;
}
}  

答案 1 :(得分:0)

资源通常都是战争的。这就是为什么你在文件系统中找不到它们的原因。虽然你仍然可以使用classloader访问它们:

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

答案 2 :(得分:0)

Spring可以使用Resource interface:

访问底层资源
@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
}

答案 3 :(得分:0)

您可以使用ServletContext阅读该文件。 e.g。

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

另外,请检查一下 - ServletContext and Spring MVC