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 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;

public class ImageServlet implements HttpRequestHandler {

    private UserService UserService;

    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.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 = > 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 {
                } catch (IOException ignore) {
            if (input != null)
                try {
                } catch (IOException ignore) {


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


Usage in JSP

<img src="image/avatar" height="75px" width="75px" align="left" />

The code is pretty self-explanatory:

  • get the byte[] array from the database
  • wrap it with an InputStream
  • write the data from the InputStream to the servlet output stream in chunks

This code version supposes that you want to display the avatar of the current logged user. But this servlet can be used with any type of situation. For example, if you want to display images by the imageId, you can do this:

<img src="image/1212" height="75px" width="75px" align="left" />

Where 1212 is the imageId. You can then grab this imageId in the servlet, get the corresponding byte[] from the DB and continue as in the above code.

Nice, elegant and easy.

If you have questions please leave a comment below.


10 thoughts on “How to display images from the database in your jsp pages – the easy way

  1. Cool.
    As long as some form of caching is in place.
    If the image comes from the database and you’re using Hibernate for example, then we can assume the BLOB is only retrieved once. Would be painful otherwise. Try to test with some OS-cache web caching tags also. Or using Spring’s GemFire

    Another interesting point here: shouldn’t the servlet report the lastModified HTTP header for the image? So that the browser may cache the image itself and don’t call the servlet each time. Woth checking

    1. Server side caching is definitely needed, depending of the types of pictures you want to handle.
      On the client side, all caching headers should/can be used (depending of situations): Last-Modified, Expires, ETag or If-Modified-Since.
      The example is focused on how to implement this, rather than how to tweak its performance.

  2. Hi ludovicianul,
    I want to merge two image vertically in JSp/Servlet/Java. can you please help me out on this issue.

      1. I am trying to getting images from db. getting the images from db is done but need to merge vertically in JSP page and what do you mean offline merge.

      2. I am trying to getting images from db. getting the images from db is done but need to merge vertically in JSP page and what do you mean by offline merge please be specifc.

      3. By offline I mean manually merge them.
        You could try the following:
        BufferedImage image = File(path, “image.png”));
        BufferedImage overlay = File(path, “overlay.png”));

        // create the new image, canvas size is the max. of both image sizes
        int w = Math.max(image.getWidth(), overlay.getWidth());
        int h = Math.max(image.getHeight(), overlay.getHeight());
        BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

        // paint both images, preserving the alpha channels
        Graphics g = combined.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.drawImage(overlay, 0, 0, null);

        // Save as new image
        ImageIO.write(combined, “PNG”, new File(path, “combined.png”));

  3. this example was nice….but im doing web project to retrive the employee details with image from database using jsp servlet.can u help me out of this……….

  4. Hi, Nice article. Is there any where to download the full code. What methods have you created in the UserDao and service to perform image display? I’m using spring 4 and Hibernate 4 but keen to include servlets.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s