Java Servlet serve plain text

last modified August 24, 2023

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.

├── main
│   ├── java
│   │   └── com
│   │       └── zetcode
│   │           ├── util
│   │           │   └── ReadTextUtil.java
│   │           └── web
│   │               └── GetText.java
│   ├── resources
│   │   └── thermopylae.txt
│   └── webapp
│       └── index.html
└── test
    └── java

This is the project structure.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"










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

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 java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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 {


        ServletOutputStream sout = response.getOutputStream();
        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.

ServletOutputStream sout = response.getOutputStream();

We get the ServletOutputStream 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.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ReadTextUtil {

    public static String getContents()  {

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

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

        if (url == null) {
            data = "no text data found";

        try {
            data = Files.readString(Paths.get(url.toURI()), StandardCharsets.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.readString(Paths.get(url.toURI()), StandardCharsets.UTF_8);

With Files.readString 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.

$ mvn jetty:run

We run the Jetty server.

$ curl -I localhost:8080/app/GetText
HTTP/1.1 200 OK
Date: Mon, 19 Sep 2022 10:53:27 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 223
Server: Jetty(11.0.11)

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.


My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java Servlet tutorials.