This is a standard way of showing an image via Servlet. However this way is not very efficient.
It will work fine for one or two images on the same page but if you have a gallery full of the thumbnails and every thumb uses
simular request – I would consider re-designing your application a bit.


<img src="domain.com/ImageServerServlet?image=test.jpg" />

ImageServerServlet will look like that:


package com.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

public class ImageServerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ImageServerServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {

		try {
			ServletContext servletContext = getServletContext();
			String fileName = request.getParameter("image");
			FileInputStream fis = new FileInputStream(new File(servletContext.getRealPath("images/" + fileName)));
			BufferedInputStream bis = new BufferedInputStream(fis);
			response.setContentType("image/jpeg");
			BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
			for (int data; (data = bis.read()) > -1;) {
				output.write(data);
			}
		} catch (IOException e) {

		}

	}

}

Dima Svirid

Software architect, JAVA, Spring, Hibernate, AngularJs, Backbone, MongoDB, Oracle. CTO and Co-Founder of Homeadnet.com

More Posts

Follow Me:

Tagged with: