繁体   English   中英

如何从Java项目的resource / images文件夹加载图像?

[英]how to load image from java project's resource/images folder?

我正在Sprng MVC中开发一个购物车,卖家可以从那里上传带有说明的产品图片。 我可以将图像上传到webapp/resources/images文件夹。 现在,当任何用户打开我的网站时,我必须将所有这些图像加载到仪表板页面(主页)。 我无法从此位置加载这些图像。

在我的jsp中,我正在编写如下最终代码:

<img src="resources/images/product1.jpg"/>

如何将这个文件夹添加到classpath以便可用。 我正在使用Spring MVC和MAVEN。

请让我知道如何实现这一目标。

使用JSP中的表达语言(EL)

<img src="${pageContext.request.contextPath}/resources/images/product1.jpg"/>

据我了解,您已将图像上载到服务器上的单独文件夹,并且希望将该文件夹包括在类路径中,以在JSP上检索和显示图像。

在Spring MVC中,您可以通过在URL资源前添加'file:'前缀来强制使用绝对路径(相对于系统根目录):

// 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");

这相对于当前工作目录有效。图像将从文件系统位置(在这种情况下相对于当前工作目录)加载。 因此,我们已将目录添加到classpath。 同样,您也可以在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中, 如果没有Context路径,它将自动添加。

我能够解决此问题:在Spring配置中添加了以下资源声明

<resources mapping="/resources/**" location="/resources/" />

并在jsp中

<img src="<c:url value="/resources/images/product1.jpg" />" alt="" />

谢谢大家的帮助,您的指导确实帮助我获得了此问题的答案。

暂无
暂无

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

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