在Spring Controller中加载静态文件 [英] Load a static file in a Spring Controller

查看:156
本文介绍了在Spring Controller中加载静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Spring很陌生,如果我在这里看不到明显的答案,请道歉。

I'm pretty new to Spring, so apologies if I don't see the obvious answer here.

我使用Spring MVC控制器设置了一个小型演示项目,并将其部署到App Engine。在我的控制器中,我想将静态文件的内容读入String。这样做的最佳方式是什么?

I set up small demo project with a Spring MVC controller and deployed it to App Engine. In my controller I would like to read the content of a static file into a String. What's the best way of doing that?

我用谷歌搜索了一下,但我可能正在寻找错误的东西。我尝试了以下,但它不起作用:

I googled a bit but I'm probably searching for the wrong thing. I tried the below, but it does not work:

@Controller
@RequestMapping("/myController")
public class MyController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public @ResponseBody String myTest() {

        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        String content = "";
        try {
            fileReader = new FileReader("file:/WEB-INF/content/somecontent.txt");
            bufferedReader = new BufferedReader(fileReader);
            content = bufferedReader.readLine();
            bufferedReader.close(); 
        }
        catch (Exception ignored) { 
            // ignore
        }
        return content;
    }
}

任何向正确方向的推动都将受到高度赞赏: - )

Any push into the right direction will be highly appreciated :-)

推荐答案

使用FileReader时,符号file:和classpath:不正确。
我建议你创建一个FileSystemResource

The notation "file:" and "classpath:" isn't right with FileReader. I suggest you to create a FileSystemResource

FileSystemResource resource = new FileSystemResource("/WEB-INF/content/somecontent.txt");

然后使用getFile()或getInputStream()来读取文件。
这在Web应用程序中非常有用,因为您可以使用相对路径。

and then to use getFile() or getInputStream() to read file. This is very useful in a web application, because you can use relative path.

这篇关于在Spring Controller中加载静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆