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

Spring Boot使用@Endpoint返回HTML时仅返回字符串如何解决

问题原因

你当前使用的Spring Boot Actuator @Endpoint 默认返回的响应头Content-Type为application/json/application/octet-stream,浏览器会将返回的HTML字符串识别为纯文本内容,不会触发页面渲染逻辑。

解决方案

仅需修改方法返回值为ResponseEntity,手动指定响应头的Content-Type为text/html即可,无需引入@Controller系列注解或模板引擎:

修改后代码

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

@Endpoint(id="welcome")
@Component
public class UtilClass {

    @ReadOperation
    public ResponseEntity<String> logger() {
        // 指定响应头为HTML类型
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_HTML);
        // 你的HTML内容
        String html = "<html><table>sampletable</table></html>";
        return new ResponseEntity<>(html, headers, 200);
    }
}

补充配置确认

确保你已经在配置文件中暴露了自定义端点,以application.properties为例:

management.endpoints.web.exposure.include=welcome

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:15:03