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
相关产品推荐
相关产品推荐

