You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Spring Boot实现页面div更新并返回纯文本响应?

在Spring Boot控制器中返回纯文本响应的几种方法

别担心,Spring Boot里实现返回纯文本(或者HTML片段)来更新前端div的需求其实很简单,给你几个实用的方案:

1. 用@ResponseBody直接返回字符串

这是最直接的方式,@ResponseBody注解会告诉Spring跳过视图解析,直接把返回的字符串作为响应体输出:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TextResponseController {

    @GetMapping("/update-content")
    @ResponseBody
    public String getUpdatedContent() {
        // 这里可以是你要返回的纯文本、HTML片段,比如从数据库或业务逻辑生成的内容
        return "<p>这是从Spring Boot返回的更新内容🎉</p>";
    }
}

注意:如果你的控制器已经用了@RestController,其实可以不用额外加@ResponseBody,因为@RestController本身就包含了@ResponseBody的功能~

2. 指定响应类型(更严谨)

如果需要明确指定响应的Content-Type(比如text/plain或text/html),可以在请求映射注解里加上produces参数,避免编码或类型识别问题:

@GetMapping(value = "/get-html-content", produces = "text/html; charset=UTF-8")
public String getHtmlContent() {
    return "<div class='new-content'>这是带样式的HTML内容</div>";
}

这样响应头里会明确标记Content-Type: text/html; charset=UTF-8,前端处理起来更稳妥。

3. 用ResponseEntity自定义响应(灵活控制)

如果需要自定义响应状态码、响应头,比如返回404或者添加自定义头信息,可以返回ResponseEntity<String>:

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomResponseController {

    @GetMapping("/custom-text-response")
    public ResponseEntity<String> getCustomText() {
        String content = "这是自定义的纯文本响应";
        return ResponseEntity.ok()
                .header("X-Custom-Header", "MyCustomValue")
                .contentType(org.springframework.http.MediaType.TEXT_PLAIN)
                .body(content);
    }
}

前端配合调用示例

你原来的JS思路是对的,这里给你补充一个用fetch的完整示例(比XMLHttpRequest更简洁):

// 发起请求获取Spring Boot返回的内容
fetch('/update-content')
    .then(response => {
        if (!response.ok) {
            throw new Error('请求失败');
        }
        return response.text(); // 解析为文本格式
    })
    .then(content => {
        // 更新目标div的内容
        document.getElementById("myDiv").innerHTML = content;
    })
    .catch(error => {
        console.error('更新内容出错:', error);
    });

内容的提问来源于stack exchange,提问作者Bobby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:53:32