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

Spring Boot返回HTML页面时仅映射实体指定字段的实现方法

实现方案

按实现成本和灵活性排序,你可以选最适配自身场景的方式:

方案1:使用Thymeleaf模板引擎直接渲染HTML(最符合返回HTML页面的需求)

这是Spring Boot生态下最常用的服务端页面渲染方案,不需要单独部署前端项目,直接在服务端把数据填充到HTML模板里返回,完全可控展示哪些字段。

  1. 引入Thymeleaf依赖,Maven项目在pom.xml中添加:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 修改原有Controller方法,将查询到的数据传入模型,指定返回的模板名:
@GetMapping("/getRandomSummerCamps")
public String getRandomSummerCamps(Model model) {
    List<AdventureHolidays> campList = adventureHolidaysService.getRandomSummerCamps();
    model.addAttribute("camps", campList);
    return "summerCampList"; // 对应templates目录下的模板文件名
}
  1. 在src/main/resources/templates路径下新建summerCampList.html模板,只取title和description字段渲染即可,多余字段不会出现在最终返回的HTML中:
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>随机夏令营列表</title>
    <style>.camp-item{margin: 20px 0; padding: 15px; border-bottom: 1px solid #eee;}</style>
</head>
<body>
    <h1>夏令营列表</h1>
    <div class="camp-item" th:each="camp : ${camps}">
        <h3 th:text="${camp.title}">夏令营标题占位</h3>
        <p th:text="${camp.description}">夏令营描述占位</p>
    </div>
</body>
</html>

启动项目访问该接口,就能直接看到只展示标题和描述的HTML页面。

方案2:使用DTO/VO投影过滤字段(适合同时需要返回精简JSON和HTML的场景)

如果你不想在模板里直接操作原始实体,或者其他接口也需要返回仅包含这两个字段的JSON,建议单独定义精简视图类,从Service层就只返回需要的字段,避免多余字段泄露:

  1. 新建只包含目标字段的VO类:
public class SummerCampSimpleVO {
    private String title;
    private String description;

    // 全参构造函数、getter方法
    public SummerCampSimpleVO(String title, String description) {
        this.title = title;
        this.description = description;
    }

    public String getTitle() {return title;}
    public String getDescription() {return description;}
}
  1. 修改Service层方法,将查询到的原始实体转换为VO列表返回:
public List<SummerCampSimpleVO> getRandomSummerCamps() {
    // 保留你原有的查询逻辑
    List<AdventureHolidays> originList = adventureHolidaysRepository.getRandomRecords();
    // 转换时只取需要的两个字段
    return originList.stream()
            .map(camp -> new SummerCampSimpleVO(camp.getTitle(), camp.getDescription()))
            .toList();
}

后续不管是把这个VO列表传给模板渲染HTML,还是直接返回JSON,都只会包含title和description两个字段,不会影响其他使用原始AdventureHolidays实体的接口。

不推荐的方案:在原始实体上加序列化忽略注解

你可以直接在AdventureHolidays实体类不需要返回的字段上加@JsonIgnore注解,这样序列化JSON的时候会自动忽略这些字段:

@Id
@JsonIgnore
private String id;
private String title;
private String description;
@JsonIgnore
private String typeOfAdventureHolidays;

但这种方式会全局生效,所有返回该实体的接口都会忽略被标记的字段,如果你其他接口需要用到id或者typeOfAdventureHolidays字段就会出问题,灵活性很差,非必要不要用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 05:24:28