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
    │   │           │   └──
    │   │           └── web
    │   │               └──
    │   ├── resources
    │   │   └── thermopylae.txt
    │   └── webapp
    │       ├── index.html
    │       └── META-INF
    │           └── context.xml
    └── test
        └── java

This is the project structure.

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







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).

<?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.

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.
package com.zetcode.web;

import com.zetcode.util.ReadTextUtil;
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 {

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


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


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.


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.


The text content is written to the writer.
package com.zetcode.util;

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.

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

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