In HTML, an image is to be represented by the <img>
element. It has a src
attribute which should point to an URL of the image. The URL should point to a servlet which returns a single image by the given path in URL http://example.com/imageservlet/filename.gif or by a request parameter in URL http://example.com/imageservlet?id=123.
Your functional requirement is apparently to show them all in a single JSP page. To achieve this, you need to print multiple <img>
elements, each pointing to a different unique image. Assuming that it's the image's filename which is unique in the database, you need to collect them in a List<String>
first. You can do this in doGet()
method of another servlet which in turn forwards the request to JSP for display:
List<String> imageNames = imageDAO.listNames();
request.setAttribute("imageNames", imageNames);
request.getRequestDispatcher("/WEB-INF/images.jsp").forward(request, response);
The listNames()
method should basically return the result of SELECT name FROM pictures
in flavor of a List<String>
. Then in the JSP you can use JSTL c:forEach
tag to iterate over imageNames
and print a separate <img>
element for each with the name in the URL.
<c:forEach items="${imageNames}" var="imageName">
<img src="imageservlet/${imagename}">
</c:forEach>
Finally, in the doGet()
of the imageservlet which is mapped on an url-pattern
of /imageservlet/*
, obtain the imagename by HttpServletRequest#getPathInfo()
.
String imagename = request.getPathInfo().substring(1);
InputStream input = imageDAO.find(imagename);
OutputStream output = response.getOutputStream();
// Write input to output the usual Java IO way.
The find()
method should basically return the result of SELECT image FROM pictures WHERE name = ?
.
To get it to run, just open the URL of the first servlet. E.g. http://example.com/images when it's mapped on an url-pattern
of /images
. It will obtain the names, forward to JSP, let JSP display multiple <img>
elements, which each in turn calls the imageservlet to obtain the image content.