How to display images from the database in your jsp pages – the easy way

The easiest and elegant way to read images from the database and display them in the UI is through a servlet that handles the image processing for you. I’ll present below a sample that displays a user avatar in the jsp page. This sample uses Spring 3 and the tip from this article to inject a spring bean into this servlet. This example can easily be adapted to many kinds of situations. Here is the code:

The servlet

package insidecoding.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;

import insidecoding.service.UserService;

@Component("imageServlet")
public class ImageServlet implements HttpRequestHandler {

    @Autowired
    private UserService UserService;

    @Override
    public void handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // get the thumb from the user entity
        byte[] thumb = userService.getCurrentUserAvatar();

        String name = "userAvatar";
        response.setContentType("image/jpeg");
        response.setContentLength(thumb.length);

        response.setHeader("Content-Disposition", "inline; filename=\"" + name
                + "\"");

        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            input = new BufferedInputStream(new ByteArrayInputStream(thumb));
            output = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[8192];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (IOException e) {
            System.out.println("There are errors in reading/writing image stream "
                    + e.getMessage());
        } finally {
            if (output != null)
                try {
                    output.close();
                } catch (IOException ignore) {
                }
            if (input != null)
                try {
                    input.close();
                } catch (IOException ignore) {
                }
        }

    }
}

Map this servlet to the /image path in web.xml

     <servlet>
        <servlet-name>imageServlet</servlet-name>
        <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>imageServlet</servlet-name>
        <url-pattern>/image/*</url-pattern>
    </servlet-mapping>

Usage in JSP Continue reading