How to Display Image Using Servlet in Java


This article explains how to display an image using a servlet in Java. The NetBeans IDE is used for the sample example.

Start creating this app

We need to create the following files:

  1. HTML File
  2. Servlet File
  3. XML File

1. HTML File

This file is used to create the user interface where the user clicks on a link to get the image.

2. Servlet File

This file is used to write an image on a browser window.

3. XML file

This file is used to configure the servlet file to the server.

The following is the procedure to create this application.

Step 1

Open the Netbeans IDE.

NetBeans IDE

Step 2

Choose "Java web" -> "web application" as in the following.

Java Web Application

Step 3

Type your project named as "ImageApp" as in the following.


Step 4

Select the Java version and the server wizard as in the following.

Server and Version Wizard

Step 5

Now delete your default "index.jsp" file and create a new "index.html" file and provide the following code for it.


<!DOCTYPE html>



        <title>Image Application</title>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta name="viewport" content="width=device-width">


    <body bgcolor="pink">

    <center><h1>Click on Below Link to View Your Image</h1>

        <a href="ImageServlet">Click Here To View Your Image</a>



Step 6

Now create a servlet file named "ImageServlet" and provide the following code for it.


import javax.servlet.*;

import javax.servlet.http.*;


public class ImageServlet extends HttpServlet {



    protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {


        ServletOutputStream out;

        out = response.getOutputStream();

        FileInputStream flinp = new FileInputStream("e:\\a.jpg");

        BufferedInputStream buffinp = new BufferedInputStream(flinp);

        BufferedOutputStream buffoup = new BufferedOutputStream(out);

        int ch=0;

        while (( != -1) {









Step 7

Now compare your default "web.xml" file with the following code.


<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.0" xmlns="" xmlns:xsi="" xsi:schemaLocation="">















Step 8

Now your project is ready to run.

Right-click on the project menu then select Run. The following output will be shown.


Step 9

Click on the given link; the following image will be shown there.

Image Display

Up Next
    Ebook Download
    View all
    View all