java - Spring 。访问webapp\resources目录

标签 java spring file spring-mvc io

我编写了以下 Spring Controller :

@RequestMapping(method = RequestMethod.GET, value = "/getVideoIcon")
    @ResponseBody
    public FileSystemResource getVideoIcon() throws IOException {
        return new FileSystemResource(new File("/resources/images/video_icon.png"));
    }

该文件位于src\main\webapp\resources\images

当我调用 Controller 时,出现以下错误:

HTTP Status 500 - resources\images\video_icon.png (The system cannot find the path specified)

请帮助纠正我的错误。

最佳答案

如果需要获取原项目的路径,应该使用getServletContext().getRealPath

@RequestMapping(method = RequestMethod.GET, value = "/getVideoIcon")
@ResponseBody
public FileSystemResource getVideoIcon(HttpServletRequest request) throws IOException {
    String path = request.getSession().getServletContext().getRealPath("/resources/images")+"/video_icon.png";
    return new FileSystemResource(new File(path));
}

如果您需要检查 path 变量所保存的内容,请在 return 语句之前使用 System.out.println(path);。如果您在尝试上述代码后仍然遇到错误消息,请随时询问..

关于java - Spring 。访问webapp\resources目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28397447/

相关文章:

java - 空白的 Java 安全策略文件是否是最严格的?

java - 如何使用 MongoTemplate 应用多个标准条件

java - Spring MVC - 在任何人进入网页之前做某事

c - 我怎么知道统计失败的原因?

java - Statement.executeUpdate() 返回 -1 是什么意思?

java - MyEclipse 没有将链接源部署到 WEB-INF/classes

java - 表格 :errors not displaying errors on JSP in Spring

java - Spring Data JPA 自定义方法排序

python读取文件操作

java - 如何在 Java 中将文本文件的整数行分配到 2D 表中?