更新时间:2023-11-11 21:12:34
首先,JSP是一种视图技术,提供了一个模板来编写HTML / CSS / JS和能够与后端Java代码交互以控制页面流和访问后端数据。你的问题更多的是HTML。
First, JSP is a view technology providing a template to write HTML/CSS/JS in and the ability to interact with backend Java code to control page flow and access backend data. Your problem is more in HTML.
现在,要在HTML页面中显示图像,您需要HTML < img>
元素。要定义/分配图像,您只需要让 src
属性指向一个URL。例如,
Now, to display an image in a HTML page, you need the HTML <img>
element. To define/allocate an image, you just have to let the src
attribute point to an URL. E.g.
<img src="url/to/image.jpg">
(它可以相对于当前上下文,也可以是绝对URL,例如以 http:// )
(it can be either relative to the current context, or an absolute URL, e.g. starting with http://
)
如果图像是动态的,就像你的情况一样,你需要一个 Servlet
,它侦听匹配图像URL的 url-pattern
。例如,
If the image is dynamic, as in your case, you need to have a Servlet
which listens on the url-pattern
matching the image URL. E.g.
<img src="imageservlet/image.jpg">
(这里的servlet显然要映射到 / imageservlet / *
和图像标识符,这里是文件名,在这里可以通过 request.getPathInfo()
)
(here the servlet is obviously to be mapped on /imageservlet/*
and the image identifier, here the filename, is here available by request.getPathInfo()
)
< img src>
将触发GET请求,因此您只需实现 doGet()
servlet的方法。要发送HTTP响应,您需要做的就是将一些内容写入响应的 OutputStream
,以及一组代表内容的响应头( Content-Type
, Content-Length
和/或 Content-disposition
)。您可以使用 ImageIO#write()
写一个 BufferedImage
到 OutputStream
。
The <img src>
will fire a GET request, so you just have to implement doGet()
method of the servlet. To send a HTTP response all you need to do is to write some content to the OutputStream
of the response, along with a set of response headers representing the content (Content-Type
, Content-Length
and/or Content-disposition
). You can use ImageIO#write()
to write a BufferedImage
to an OutputStream
.
您可以找到这种图像servlet的基本示例这里。您只需要用 Files#copy() /ImageIO.html#write-java.awt.image.RenderedImage-java.lang.String-java.io.OutputStream-rel =nofollow noreferrer> ImageIO#write()
。
You can find a basic example of such an image servlet here. You just have to replace Files#copy()
with ImageIO#write()
.
response.setContentType("image/png");
ImageIO.write(bufferedImage, "png", response.getOutputStream());