Home  >  Q&A  >  body text

Retrieving and displaying images from a database in a JSP page: a step-by-step guide

<p>How to retrieve and display images from the database in a JSP page? </p>
P粉191610580P粉191610580419 days ago648

reply all(1)I'll reply

  • P粉251903163

    P粉2519031632023-08-28 18:47:50

    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()< /a> 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/*< URL 模式上的 GET 请求/code>, 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:

    reply
    0
  • Cancelreply