ZetCode

Java Servlet 提供纯文本

最后修改于 2023 年 8 月 24 日

在 Java Servlet 文本教程中,我们展示了如何从 Java Servlet 返回纯文本。Web 应用程序部署在 Jetty 上。

Servlet 是一个 Java 类,它响应特定类型的网络请求——最常见的是 HTTP 请求。Java Servlet 用于创建 Web 应用程序。它们在 Servlet 容器(如 Tomcat 或 Jetty)中运行。现代 Java Web 开发使用构建在 Servlet 之上的框架。

Jetty 是 JBoss 的一个开源 Java Servlet 容器。它可以在嵌入式模式下使用。

Java Servlet 应用程序

以下 Web 应用程序使用 Java Servlet 将纯文本发送到客户端。文本从资源目录中的文件中读取。

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

这是项目结构。

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

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

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

    </dependencies>

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

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

        </plugins>
    </build>

</project>

这是 pom.xml 文件。

这是 Maven POM 文件。jakarta.servlet-api 依赖项是用于 Servlet 的。

maven-war-plugin 负责收集 Web 应用程序的所有工件依赖项、类和资源,并将它们打包成 Web 应用程序存档(WAR)。jetty-maven-plugin 是一个有用的 Maven 插件,用于快速开发和测试。它创建一个 Web 应用程序,启动一个 Jetty Web 服务器,并将应用程序部署到服务器上。

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.

这是要从 Web 应用程序读取并发送到客户端的文本文件。

com/zetcode/web/GetText.java
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 {

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

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

        ServletOutputStream sout = response.getOutputStream();
        String content = ReadTextUtil.getContents();

        sout.print(content);
    }
}

这是 GetText Servlet。它从资源目录中的文本文件中读取数据,并将文本以纯文本格式发送到客户端。

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

我们将响应对象的 content type 设置为 text/plain

ServletOutputStream sout = response.getOutputStream();

我们获取 ServletOutputStream,它用于将字符文本发送到客户端。

String content = ReadTextUtil.getContents();

我们将文本读取到 content 变量中。

sout.print(content);

文本内容被写入 writer。

com/zetcode/util/ReadTextUtil.java
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 是一个用于读取文件内容的实用类。

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

我们使用 getResource 方法获取文件资源。

data = Files.readString(Paths.get(url.toURI()), StandardCharsets.UTF_8);

使用 Files.readString 方法一次性读取整个文件。

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>

这是主页。它包含一个调用 GetText Servlet 的链接。

$ mvn jetty:run

我们运行 Jetty 服务器。

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

我们使用 curl 命令获取响应头。从服务器输出中我们可以看到 content type 是 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.

我们检索文本。

在本文中,我们从 Java Servlet 发送了文本数据。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。到目前为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有超过十年的经验。

列出所有 Java Servlet 教程