原文: http://zetcode.com/articles/javaservlettext/

在 Java Servlet 文本教程中,我们展示了如何从 Java Servlet 返回纯文本。 该 Web 应用已部署在 Tomcat 服务器上。

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

Apache Tomcat 是由 Apache 软件基金会(ASF)开发的开源 Java Servlet 容器。 它是最流行的 Java Web 服务器。

Java servlet 应用

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

  1. $ tree
  2. .
  3. ├── pom.xml
  4. └── src
  5. ├── main
  6. ├── java
  7. └── com
  8. └── zetcode
  9. ├── util
  10. └── ReadTextUtil.java
  11. └── web
  12. └── GetText.java
  13. ├── resources
  14. └── thermopylae.txt
  15. └── webapp
  16. ├── index.html
  17. └── META-INF
  18. └── context.xml
  19. └── test
  20. └── java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>ServletPlainText</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11. <name>ServletPlainText</name>
  12. <properties>
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. <maven.compiler.source>1.8</maven.compiler.source>
  15. <maven.compiler.target>1.8</maven.compiler.target>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>javax.servlet</groupId>
  20. <artifactId>javax.servlet-api</artifactId>
  21. <version>3.1.0</version>
  22. <scope>provided</scope>
  23. </dependency>
  24. <dependency>
  25. <groupId>com.google.guava</groupId>
  26. <artifactId>guava</artifactId>
  27. <version>21.0</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>com.google.code.gson</groupId>
  31. <artifactId>gson</artifactId>
  32. <version>2.8.0</version>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <plugins>
  37. <plugin>
  38. <groupId>org.apache.maven.plugins</groupId>
  39. <artifactId>maven-war-plugin</artifactId>
  40. <version>2.3</version>
  41. <configuration>
  42. <failOnMissingWebXml>false</failOnMissingWebXml>
  43. </configuration>
  44. </plugin>
  45. </plugins>
  46. </build>
  47. </project>

这是 Maven POM 文件。 我们有三个工件:用于 servlet 的javax.servlet-api,用于 Java JSON 处理的gsonguava通用库。 maven-war-plugin负责收集 Web 应用的所有工件依赖项,类和资源,并将它们打包到 Web 应用存档(WAR)中。

context.xml

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

在 Tomcat context.xml文件中,我们定义了上下文路径。 它是 Web 应用的名称。

thermopylae.txt

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

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

GetText.java

  1. package com.zetcode.web;
  2. import com.zetcode.util.ReadTextUtil;
  3. import java.io.IOException;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.ServletOutputStream;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. @WebServlet(name = "GetText", urlPatterns = {"/GetText"})
  11. public class GetText extends HttpServlet {
  12. @Override
  13. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  14. throws ServletException, IOException {
  15. response.setContentType("text/plain;charset=UTF-8");
  16. ServletOutputStream sout = response.getOutputStream();
  17. String content = ReadTextUtil.getContents();
  18. sout.print(content);
  19. }
  20. }

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

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

我们将响应对象的内容类型设置为text/plain

  1. ServletOutputStream sout = response.getOutputStream();

我们得到了ServletOutputStream,用于将字符文本发送到客户端。

  1. String content = ReadTextUtil.getContents();

我们将文本读入content变量。

  1. sout.print(content);

文本内容被写入作者。

ReadTextUtil.java

  1. package com.zetcode.util;
  2. import com.google.common.base.Charsets;
  3. import com.google.common.io.Files;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.net.URISyntaxException;
  7. import java.net.URL;
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;
  10. public class ReadTextUtil {
  11. public static String getContents() {
  12. String data = null;
  13. String fileName = "thermopylae.txt";
  14. URL url = ReadTextUtil.class.getClassLoader().getResource(fileName);
  15. try {
  16. data = Files.toString(new File(url.toURI()), Charsets.UTF_8);
  17. } catch (IOException | URISyntaxException ex) {
  18. Logger.getLogger(ReadTextUtil.class.getName()).log(Level.SEVERE, null, ex);
  19. }
  20. return data;
  21. }
  22. }

ReadTextUtil是用于读取文件内容的工具类。

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

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

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

我们使用 Guava 的Files.toString()方法一次读取整个文件。

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Start Page</title>
  5. <meta charset="UTF-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1">
  7. </head>
  8. <body>
  9. <a href="GetText">Get text</a>
  10. </body>
  11. </html>

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

  1. $ curl -I localhost:8084/ServletPlainText/GetText
  2. HTTP/1.1 200 OK
  3. Server: Apache-Coyote/1.1
  4. Content-Type: text/plain;charset=UTF-8
  5. Content-Length: 225
  6. Date: Fri, 24 Nov 2017 15:21:57 GMT

我们使用curl命令获取响应的标题。 从服务器输出中,我们可以看到内容类型是文本。

从 Java Servlet 提供纯文本 - 图1

图:在浏览器中显示纯文本

该图显示了 Opera 浏览器中的文本。

在本教程中,我们从 Java servlet 发送了文本数据。

您可能也对以下相关教程感兴趣: Java servlet 教程Java servlet JSON 教程Java ServletConfig教程Java Servlet PDF 教程Java HttpServletMappingJava servlet 图像教程Java Servlet HTTP 标头Java 教程