简体   繁体   English

弹簧。 访问webapp \\ resources目录

[英]Spring. access to webapp\resources directory

I have written the following spring controller: 我写了以下弹簧控制器:

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

The file is located at src\\main\\webapp\\resources\\images 该文件位于src\\main\\webapp\\resources\\images

When I invoke the controller I get following error: 当我调用控制器时,我得到以下错误:

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

Please help to correct my mistake. 请帮助纠正我的错误。

If you need to get the original project's path, you should use getServletContext().getRealPath 如果需要获取原始项目的路径,则应使用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));
}

If you need to check what the path variable is holding, use System.out.println(path); 如果需要检查path变量的含义,请使用System.out.println(path); before the return statement. 在返回声明之前。 If you're still experiencing error message after trying the above code, feel free to ask.. 如果您在尝试上述代码后仍然遇到错误消息,请随时询问..

You don't need to write a controller to support static resources in Spring application. 您不需要编写控制器来支持Spring应用程序中的静态资源。

Add this to your Spring xml configuration: 将其添加到Spring xml配置中:

<mvc:resources mapping="/image/**" location="/resources/images/" />

In JSP page, you can use it like this: 在JSP页面中,您可以像这样使用它:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<img src="<c:url value="/image/video_icon.png" />" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM