Java servlet image tutorial

In this tutorial, we create a classic web application in Java using a servlet. The servlet sends an image to the client. The web application is deployed on Tomcat server.

Servlet is a Java class which responds to a particular type of network request - most commonly an HTTP request. Servlets are used to implement web applications. They run in a servlet container such as Tomcat or Jetty. In modern-day Java web development programmers use frameworks that are built on top of servlets.

Apache Tomcat is an open source Java Servlet Container developed by the Apache Software Foundation (ASF). It is the most popular Java web server.

Application

The following web application sends an image to the client. The web application uses a Java servlet.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>ServletImage</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ServletImage</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>

The javax.servlet-api dependency is a library for building Java servlets. The maven-war-plugin collects all artifact dependencies, classes and resources of the web application and packages them into a web application archive (WAR).

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           └── web
    │   │               └── GetImage.java
    │   ├── resources
    │   └── webapp
    │       ├── images
    │       │   └── mushroom.png
    │       ├── index.html
    │       └── META-INF
    │           └── context.xml
    └── test
        └── java

With the tree command we show the project directory structure.

context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/ServletImage"/>

The context.xml file is Tomcat's configuration file. Inside the file we set the context path (the application name). The file is located in the META-INF subdirectory.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Servlet image</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="getImage">Get image</a>
    </body>
</html>

The index.html file is the home page of our application. It has a link that calls a servlet which servers an image file.

GetImage.java
package com.zetcode.web;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "GetImage", urlPatterns = {"/getImage"})
public class GetImage extends HttpServlet {

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

        OutputStream os = null;
        InputStream is = null;

        try {

            response.setContentType("image/png");
            
            ServletContext sc = getServletContext();
            is = sc.getResourceAsStream("images/mushroom.png");

            BufferedImage bi = ImageIO.read(is);
            os = response.getOutputStream();
            ImageIO.write(bi, "png", os);

        } finally {

            if (os != null) {
                os.close();
            }
            
            if (is != null) {
                is.close();
            }
        }
    }
}

The GetImage servlet returns an image file to the client.

@WebServlet(name = "GetImage", urlPatterns = {"/getImage"})

The @WebServlet annotation maps the request with getImage URL pattern to the GetImage servlet.

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

The request is a GET request, so we serve it in the doGet() method.

response.setContentType("image/png");

The image has PNG format; therefore, we set the content type of the response to image/png.

ServletContext sc = getServletContext();

We get the ServletContext, which contains a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

is = sc.getResourceAsStream("images/mushroom.png");

We get the image resource with the getResourceAsStream() method.

BufferedImage bi = ImageIO.read(is);
os = response.getOutputStream();
ImageIO.write(bi, "png", os);

We read the image resource and write it into the OutputStream of the resource.

In this tutorial, we have used a Java servlet to send an image to the client.

You might also be interested in the following related tutorials: Java servlet check box tutorial, Servlet FreeMarker JdbcTemplate tutorial, Serving image file in Spring Boot, Java tutorial, jQuery DatePicker tutorial, Apache Derby tutorial or Stripes tutorial.