Retrieving and displaying images from a database in a JSP page: a step-by-step guide
P粉191610580
P粉191610580 2023-08-27 21:30:22
0
1
765
<p>How to retrieve and display images from the database in a JSP page? </p>
P粉191610580
P粉191610580

reply all(1)
P粉251903163

Let’s step by step and see what happens:

  • JSP is basically a view technology designed to generate HTML output.
  • To display an image in HTML format, you need the HTML element.
  • To have it position an image, you need to specify its src attribute.
  • The
  • src attribute needs to point to a valid http:// URL, so not a local disk file system path file:// because when the server and client This will never work when running on a physically different machine.
  • Image URLs need to include the image identifier in the request path (e.g. http://example.com/context/images/foo.png) or as a request parameter (e.g. http:/ /example.com/context/images?id=1).
  • In the JSP/Servlet world, you can have a servlet listen to a specific URL pattern, such as /images/*, so you can execute some Java code on a specific URL.
  • Images are binary data that can be obtained from the database in the form of byte[] or InputStream, JDBC API provides ResultSet #getBytes() and ResultSet#getBinaryStream() For this purpose, JPA API provides @Lob to this end. 李>
  • In a Servlet, you just write this byte[] or InputStream to the response's OutputStream (the usual Java IO Way.
  • The client needs to be instructed to handle the data as an image, so at least the Content-Type response header needs to be set as well. You can do this via ServletContext#getMimeType() Based on the image file extension, you can do this via the extension in web.xml and/or Override this extension .

This should be. It pretty much writes the code itself. Let's start with HTML (in JSP):

<img src="${pageContext.request.contextPath}/images/foo.png">
<img src="${pageContext.request.contextPath}/images/bar.png">
<img src="${pageContext.request.contextPath}/images/baz.png">

If needed, you can also set it dynamically using EL src ="https://stackoverflow.com/tags/jstl/info">JSTL:

<c:forEach items="${imagenames}" var="imagename">
    <img src="${pageContext.request.contextPath}/images/${imagename}">
</c:forEach>

Then define/create a servlet that listens on /images/*, the following example uses plain JDBC to do the job:

@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {

    // content=blob, name=varchar(255) UNIQUE.
    private static final String SQL_FIND = "SELECT content FROM Image WHERE name = ?";

    @Resource(name="jdbc/yourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml.
    private DataSource dataSource;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String imageName = request.getPathInfo().substring(1); // Returns "foo.png".

        try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_FIND)) {
            statement.setString(1, imageName);
            
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    byte[] content = resultSet.getBytes("content");
                    response.setContentType(getServletContext().getMimeType(imageName));
                    response.setContentLength(content.length);
                    response.getOutputStream().write(content);
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
                }
            }
        } catch (SQLException e) {
            throw new ServletException("Something failed at SQL/DB level.", e);
        }
    }

}

That's it. If you are worried about HEAD and cache headers and responding to these requests correctly, use this Abstract Template for a Static Resource servlet.

See also:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template