据我了解,您已将图像上传到服务器上的单独文件夹,并且您希望将该文件夹包含在类路径中以检索和显示 JSP 上的图像。
在 Spring MVC 中,您可以通过在 'file:' 前面加上 URL 资源:
来强制使用绝对路径(相对于系统的根目录)
// actual context type doesn't matter, the Resource will always be UrlResource`
ctx.getResource("file:/root/webapp/resources/images");
或
// force this FileSystemXmlApplicationContext to load its definition via a UrlResource`
ApplicationContext ctx =
new FileSystemXmlApplicationContext("file:/root/webapp/resources/images");`
这是通过指定绝对 URL 添加图像目录的一种方法。
如果您的图像目录相对于当前目录并且想要添加到您的类路径,那么以下方法将起作用:
ApplicationContext ctx =
new FileSystemXmlApplicationContext("resources/images");
这相对于当前工作目录起作用。图像将从文件系统位置加载,在这种情况下相对于当前工作目录。因此,我们已将目录添加到类路径中。同样,您也可以在 XML 中进行类路径配置。
<mvc:resources mapping="/resources/**"
location="classpath:resources/images"
cache-period="10000" />
或
<mvc:resources mapping="/resources/**"
location="file:/root/webapp/resources/images"
cache-period="10000" />
我们现在可以在您的 JSP 中检索图像,如下所示
<img src="${pageContext.request.contextPath}/resources/images/user.jpg"/>
上面的 EL ${pageContext.request.contextPath} 确保 Context 总是在前面。
注意:在 Spring 3.2.2 中,the Context path is prepended automatically if not present.