ZetCode

Java Servlet serve plain text

last modified November 30, 2026

In Java Servlet text tutorial, we show how to return plain text from a Java servlet. The web application is deployed on Jetty.

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.

Jetty is an open source Java Servlet Container by JBoss. It can be used in embedded mode.

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.

pom.xml
src
├── main
│   ├── java
│   │   └── com
│   │       └── zetcode
│   │           ├── util
│   │           │   └── ReadTextUtil.java
│   │           └── web
│   │               └── GetText.java
│   ├── resources
│   │   └── thermopylae.txt
│   └── webapp
│       └── index.html
└── 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>JavaServletPlainText</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>6.1.0</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.5.1</version>
            </plugin>

            <plugin>
                <groupId>org.eclipse.jetty.ee11</groupId>
                <artifactId>jetty-ee11-maven-plugin</artifactId>
                <version>12.1.15</version>
                <configuration>
                    <webApp>
                        <contextPath>/app</contextPath>
                    </webApp>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project>

This is the pom.xml file.

This is the Maven POM file. The jakarta.servlet-api dependency is for servlets.

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). The jetty-ee11-maven-plugin is a useful Maven plugin for rapid development and testing. It starts a Jetty 12.1 web server and deploys the application on the server.

resources/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.

com/zetcode/web/GetText.java
package com.zetcode.web;

import com.zetcode.util.ReadTextUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

@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");

        String content = ReadTextUtil.getContents();

        if (content == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        PrintWriter out = response.getWriter();
        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.

String content = ReadTextUtil.getContents();

if (content == null) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
}

We read the text into the content variable. If the resource is missing, we return a 404 response.

PrintWriter out = response.getWriter();
out.print(content);

We get a character writer and write the text content to it.

com/zetcode/util/ReadTextUtil.java
package com.zetcode.util;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ReadTextUtil {

    public static String getContents() {

        String fileName = "thermopylae.txt";

        try (InputStream is = ReadTextUtil.class.getClassLoader()
                .getResourceAsStream(fileName)) {

            if (is == null) {
                return null;
            }

            return new String(is.readAllBytes(), StandardCharsets.UTF_8);

        } catch (IOException ex) {
            Logger.getLogger(ReadTextUtil.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
}

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

try (InputStream is = ReadTextUtil.class.getClassLoader()
        .getResourceAsStream(fileName)) {

We open the resource as an input stream with getResourceAsStream. This works both for an exploded web application and for a packed WAR.

return new String(is.readAllBytes(), StandardCharsets.UTF_8);

We read the whole file into a string using UTF-8.

webapp/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.

$ mvn jetty:run

We run the Jetty server.

$ curl -I localhost:8080/app/GetText
HTTP/1.1 200 OK
Server: Jetty(12.1.15)
Date: Mon, 30 Nov 2026 19:10:18 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 223

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

$ curl localhost:8080/app/GetText
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.

We retrieve the text.

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

Source

Jakarta Servlet specification

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Java Servlet tutorials.