Serving plain text from Java servlet

In Java Servlet text tutorial, we show how to return plain text from a Java servlet. 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. Java servlets are used to create web applications. They run in servlet containers such as Tomcat or Jetty. Modern-day Java web development uses 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.

Java servlet application

The following web application uses a Java servlet to send plain text to the client. The text is read from a file in the resources directory.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── util
    │   │           │   └── ReadTextUtil.java
    │   │           └── web
    │   │               └── GetText.java
    │   ├── resources
    │   │   └── thermopylae.txt
    │   └── webapp
    │       ├── index.html
    │       └── META-INF
    │           └── context.xml
    └── test
        └── java

This is the project structure.

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>ServletPlainText</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ServletPlainText</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>
        
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>        
        
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </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>

This is the Maven POM file. We have three artifacts: javax.servlet-api for servlets, gson for JSON processing in Java, and the guava common library. The maven-war-plugin is responsible for collecting all artifact dependencies, classes and resources of the web application and packaging them into a web application archive (WAR).

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

In the Tomcat context.xml file, we define the context path. It is the name of the web application.

thermopylae.txt
The Battle of Thermopylae was fought between an alliance of Greek city-states, 
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the 
course of three days, during the second Persian invasion of Greece. 

This is the text file to be read and sent from the web application to the client.

GetText.java
package com.zetcode.web;

import com.zetcode.util.ReadTextUtil;
import java.io.IOException;
import java.io.PrintWriter;
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 = "GetText", urlPatterns = {"/GetText"})
public class GetText extends HttpServlet {

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

        response.setContentType("text/plain;charset=UTF-8");

        try (PrintWriter out = response.getWriter()) {
            
            String content = ReadTextUtil.getContents();

            out.print(content);
        }
    }
}

This is the GetText servlet. It reads data from the text file located in the resources directory and sends the text to the client in plain text format.

response.setContentType("text/plain;charset=UTF-8");

We set the content type of the response object to text/plain.

try (PrintWriter out = response.getWriter()) {

We get the PrintWriter which is used to send character text to the client.

String content = ReadTextUtil.getContents();

We read the text into the content variable.

out.print(content);

The text content is written to the writer.

ReadTextUtil.java
package com.zetcode.util;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ReadTextUtil {

    public static String getContents()  {

        String data = null;
        String fileName = "thermopylae.txt";

        URL url = ReadTextUtil.class.getClassLoader().getResource(fileName);
        
        try {
            data = Files.toString(new File(url.toURI()), Charsets.UTF_8);
        } catch (IOException | URISyntaxException ex) {
            Logger.getLogger(ReadTextUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

        return data;
    }
}

ReadTextUtil is an utility class to read the contents of the file.

URL url = ReadTextUtil.class.getClassLoader().getResource(fileName);

We get the file resource with the getResource() method.

data = Files.toString(new File(url.toURI()), Charsets.UTF_8);

We use Guava's Files.toString() method to read the whole file in one shot.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <a href="GetText">Get text</a>
    </body>
</html>

This is the home page. It contains a link to call the GetText servlet.

$ curl -I localhost:8084/ServletPlainText/GetText
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/plain;charset=UTF-8
Content-Length: 225
Date: Wed, 17 May 2017 21:20:42 GMT

We fetch the header of the response with the curl command. From the server output we can see that the content type is text.

Showing plain text in a browser
Figure: Showing plain text in a browser

The figure shows the text in Opera browser.

In this tutorial, we have sent text data from a Java servlet.

You might also be interested in the following related tutorials: Java servlet JSON tutorial, Java servlet check box tutorial, Java servlet image tutorial, Java Servlet HTTP headers, or Java tutorial