Html 在 JSP 中加载 img

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17628945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:04:39  来源:igfitidea点击:

Load an img in a JSP

htmlimagejsp

提问by zer0uno


I'm trying to load an image dynamicaly in a JSP and I'm trying to do something like:


我正在尝试在 JSP 中动态加载图像,并且我正在尝试执行以下操作:

<img src="<%= book.img %>">

where book.img contains a string (an absolute path). How can I fix the problem? The error I receive is the following:
Bad value for attribute src on element img: DOUBLE_WHITESPACE in PATH.

其中 book.img 包含一个字符串(绝对路径)。我该如何解决这个问题?我收到的错误如下:
元素 img 上的属性 src 的错误值:PATH 中的 DOUBLE_WHITESPACE。

采纳答案by Kevin Bowersox

book.imgshould contain an absolute url to the image on the server.

book.img应该包含服务器上图像的绝对 url。

So if your images are stored in:

因此,如果您的图像存储在:

Webcontent/resources/images/

and you had an image:

你有一个图像:

close-button.png

book.imgshould = /resources/images/close-button.png

book.img应该 = /resources/images/close-button.png

Then in your JSP use JSTL to create the URL:

然后在您的 JSP 中使用 JSTL 创建 URL:

<img src="<c:url value="${book.img}"/>"/>

c:urlwill prefix the domain and context to the absolute url.

c:url将域和上下文作为绝对 url 的前缀。

Another way without JSTL is:

没有 JSTL 的另一种方法是:

 <img src="${pageContext.request.contextPath}${book.img}"/>

回答by Joe C

I tried a zillion different solutions mostly found in SO where this question is asked 3 or 4 other times. Many, many answers tell you what to write in your HTML but don't bother to tell you where that means your image file should reside. The only thing that worked for me was this:

我尝试了无数不同的解决方案,这些解决方案主要在 SO 中找到,另外 3 或 4 次问这个问题。很多很多答案会告诉您在 HTML 中写什么,但不要费心告诉您这意味着您的图像文件应该驻留在何处。唯一对我有用的是:

Put your image file directly into your 'WebContent' directory. Then your HTML in your jsp file is:

将您的图像文件直接放入您的“WebContent”目录中。然后你的jsp文件中的HTML是:

    <img src="${pageContext.request.contextPath}/myImageFileName.png">

By extrapolation I'd say that if you put the image file into a subdir such as WebContent/Images then you'd just add that subdir to the src, you can figure out how. But I didn't test that.

通过推断,我会说,如果您将图像文件放入一个子目录,例如 WebContent/Images,那么您只需将该子目录添加到 src,您就可以弄清楚如何。但我没有测试。