Spring。访问 webapp\resources 目录
Spring. access to webapp\resources directory
我编写了以下 spring 控制器:
@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)
请大家指正错误
如果需要获取原项目的路径,应该使用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);
。如果您在尝试上述代码后仍然遇到错误消息,请随时询问..
您不需要编写控制器来支持 Spring 应用程序中的静态资源。
将此添加到您的 Spring xml 配置中:
<mvc:resources mapping="/image/**" location="/resources/images/" />
在JSP页面中,可以这样使用:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<img src="<c:url value="/image/video_icon.png" />" />
我编写了以下 spring 控制器:
@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)
请大家指正错误
如果需要获取原项目的路径,应该使用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);
。如果您在尝试上述代码后仍然遇到错误消息,请随时询问..
您不需要编写控制器来支持 Spring 应用程序中的静态资源。
将此添加到您的 Spring xml 配置中:
<mvc:resources mapping="/image/**" location="/resources/images/" />
在JSP页面中,可以这样使用:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<img src="<c:url value="/image/video_icon.png" />" />