2015-02-08 57 views
2

我写了下面的弹簧控制器:春天。访问web应用程序资源目录

@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

当我调用控制器我获得以下错误:

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

请帮助纠正我的错误。

回答

5

如果你需要得到原始项目的路径,你应该如果你需要检查一下path变量控股,return语句之前使用System.out.println(path);使用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)); 
} 

。如果尝试上述代码后仍然遇到错误消息,请随时询问。

2

您不需要编写控制器来支持Spring应用程序中的静态资源。

添加到您的Spring XML配置:

​​

在JSP页面中,您可以使用它像这样:

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

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

以及如何访问该页面的资源写这之后? – gstackoverflow 2015-02-08 19:08:16

+0

您可以像在映射中定义的那样访问资源,例如。在jsp文件中:“/>并添加taglib前缀<%@ taglib prefix =”c“uri =”http://java.sun.com/jsp/jstl/core“%> – 2015-02-08 19:12:30

+0

如果我想写一个在javacode中的目录中的文件? – faisalbhagat 2016-05-06 12:16:56

相关问题