Display Images using Servlet

Display Images using Servlet

In this example, we are going to show you an example of how to display Images using Servlet. Please read our previous article where we discussed how to create a Login Form using Servlet. For this example, we are going to use ServletOutputStream class for writing the image and the FileInputStream class to read the image content. We have used the BufferedInputStream and BufferedOutputstream class to make the performance faster. Here we have to use the content type image/jpeg. We have a rose.jpeg image inside the G:\JAVA directory. You can change the location accordingly. In this example we are creating the following pages:

  1. index.html
  2. ServletIOExample.java
  3. web.xml

Here, the index.html file creates a link that invokes the servlet. The URL-pattern of the servlet is “servlet1”. ServletIOExample.java servlet class reads the image from the mentioned directory and writes the content in the response object using ServletOutputStream and BufferedOutputStream classes. Here, web.xml deployment descriptor is the configuration file of web application which instructs the servlet container which classes to load and hot to intercept requests coming from browsers.

        <title>Display Image</title>
         <a href="servlet1">click for photo</a>  
import java.io.*;  
import javax.servlet.*;  
import javax.servlet.http.*;  
public class ServletIOExample extends HttpServlet {  
    public void doGet(HttpServletRequest request,HttpServletResponse response)  
             throws IOException  
    ServletOutputStream out;  
    out = response.getOutputStream();  
    FileInputStream fin = new FileInputStream("G:/JAVA/rose.jpg");  
    BufferedInputStream bin = new BufferedInputStream(fin);  
    BufferedOutputStream bout = new BufferedOutputStream(out);  
    int ch =0; ;  
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 



Run your index.html file you will get the following output.

display image using Servlet

Click on the link to get the output

how to display image using Servlet

In the next article, I am going to discuss Auto Page Refresh using Servlet. Here, in this article, we develop an application to display image using Servlet and I hope you enjoy this how to display image using Servlet article.

Leave a Reply

Your email address will not be published. Required fields are marked *