ZetCode

Spring Boot 服务文本

最后修改时间:2023年7月20日

Spring Boot 服务文本教程展示了如何在 Spring Boot 应用程序中提供纯文本。

Spring 是一个流行的 Java 应用程序框架,而 Spring Boot 是 Spring 的一个演进,它有助于轻松创建独立的、生产级的基于 Spring 的应用程序。

内容类型

内容类型,或媒体类型,是一个与文件一起发送的字符串,指示文件的类型。它描述了内容格式;例如,HTML 文件可能被标记为 text/html,或者图像文件被标记为 image/png。它与 Windows 上的文件名扩展名具有相同的作用。

content-type 标头值用于指示资源的媒体类型。 text/plain; charset=utf-8 用于文本文件。

Spring Boot 服务文本示例

以下应用程序展示了三种向客户端发送文本的方式。

build.gradle
...
src
├── main
│   ├── java
│   │   └── com
│   │       └── zetcode
│   │           ├── Application.java
│   │           └── controller
│   │               └── MyController.java
│   └── resources
└── test
    ├── java
    └── resources

这是项目结构。

build.gradle
plugins {
    id 'org.springframework.boot' version '3.1.1'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

这是 Gradle 构建文件。我们只需要 spring-boot-starter-web 依赖项。

com/zetcode/controller/MyController.java
package com.zetcode.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;


@Controller
public class MyController {

    @GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
    public @ResponseBody
    String home() {

        return "home page";
    }

    @GetMapping(value = "/about")
    public void test(HttpServletResponse response) throws IOException {

        response.addHeader("content-type", "text/plain; charset=utf-8");
        response.setStatus(200);

        PrintWriter out = response.getWriter();
        out.println("about page");
    }

    @GetMapping(value = "/contact")
    public ResponseEntity<String> contact() {

        var httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));

        return new ResponseEntity<>("contact page", httpHeaders, HttpStatus.OK);
    }
}

我们有三种在控制器中返回文本的方法。每种方法都使用不同的技术。

@Controller
public class MyController {

    @GetMapping(value = "/", produces = MediaType.TEXT_PLAIN_VALUE)
    public @ResponseBody
    String home() {

        return "home page";
    }

由于控制器使用 @Controller 注解,我们必须添加 @ResponseBody 注解以直接写入响应的主体,而不是返回要处理的视图名称。 home 方法具有 String 返回类型,并且 produces 属性设置为 MediaType.TEXT_PLAIN_VALUE

@GetMapping(value = "/about")
public void test(HttpServletResponse response) throws IOException {

    response.addHeader("content-type", "text/plain; charset=utf-8");
    response.setStatus(200);

    PrintWriter out = response.getWriter();
    out.println("about page");
}

第二种方式使用 HttpServletResponse。这是一种低级方法,我们直接写入响应对象。

@GetMapping(value = "/contact")
public ResponseEntity<String> contact() {

    var httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));

    return new ResponseEntity<>("contact page", httpHeaders, HttpStatus.OK);
}

在第三种情况下,我们使用 ResponseEntity 来提供文本。媒体类型在 HttpHeaders 中设置。

com/zetcode/Application.java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application  {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Application 是设置 Spring Boot 应用程序的入口点。

我们使用 ./gradlew bootRun 运行应用程序。

$ curl localhost:8080
home page
$ curl localhost:8080/about
about page
$ curl localhost:8080/contact
contact page

这是所有三个页面的输出。

$ curl -i localhost:8080/contact
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 12
Date: Thu, 20 Jul 2023 09:44:07 GMT

contact page

使用 curl 的 -i 选项,我们还包括标头。

在本文中,我们展示了如何从 Spring Boot 应用程序向客户端发送文本数据。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 Spring Boot 教程