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

如何在Spring Boot Controller中返回HTML页面并展示数据库查询数据

Spring Boot返回HTML并展示电影数据的实现方案

你可以根据自己的业务场景选择以下两种实现方式:

方案1:服务端渲染(推荐轻量场景,使用Thymeleaf模板引擎)

这种方式无需额外的前端异步请求,服务端直接把数据填充到HTML后返回给浏览器。

步骤1:引入Thymeleaf依赖

在你的pom.xml(Maven项目)中添加starter依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

如果是Gradle项目,在build.gradle中添加:

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

步骤2:修改Controller逻辑

首先把Controller类上的@RestController注解改为@Controller(@RestController默认所有方法返回JSON,不会走视图解析),然后修改你的GetMapping接口:

@Controller
public class MovieController {

    @Autowired
    private MovieService movieService;

    @GetMapping
    public String getMoviesPage(Model model) {
        // 把电影列表数据放到模型中,传递给模板
        model.addAttribute("movies", movieService.getMovies());
        // 返回HTML模板的文件名(不需要加.html后缀,Thymeleaf会自动匹配)
        return "movies";
    }
}

如果你不想修改类上的@RestController注解,也可以让方法返回ModelAndView对象:

@GetMapping
public ModelAndView getMoviesPage() {
    ModelAndView mav = new ModelAndView("movies");
    mav.addObject("movies", movieService.getMovies());
    return mav;
}

步骤3:编写HTML模板

在src/main/resources/templates目录下新建movies.html文件,内容示例:

<!DOCTYPE html>
<!-- 引入Thymeleaf命名空间 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>电影列表</title>
</head>
<body>
    <h1>热门电影</h1>
    <div id="movieList">
        <!-- 遍历movies集合,渲染每一条电影数据 -->
        <div th:each="movie : ${movies}" style="border:1px solid #eee; margin:10px 0; padding:10px;">
            <h3 th:text="${movie.title}"></h3>
            <p>上映日期:<span th:text="${movie.releaseDate}"></span></p>
            <p>评分:<span th:text="${movie.rating}"></span></p>
        </div>
    </div>
</body>
</html>

启动项目访问接口,就能直接看到带电影数据的HTML页面了。

方案2:前后端分离模式(保留原JSON接口,前端异步请求数据)

这种方式适合需要前后端独立开发的场景,你可以保留原有的返回JSON的接口,额外加一个返回HTML的接口即可。

步骤1:调整Controller接口

给原有的返回JSON的接口加个单独的请求路径,再新增一个返回HTML页面的接口:

@RestController
public class MovieController {

    @Autowired
    private MovieService movieService;

    // 保留原JSON接口,路径改为/api/movies供前端调用
    @GetMapping("/api/movies")
    public List<Movie> getMovies(){
        return movieService.getMovies();
    }

    // 新增接口返回HTML页面
    @GetMapping("/movies")
    public ModelAndView getMoviesPage(){
        return new ModelAndView("movies.html");
    }
}

步骤2:编写HTML页面(原生JS实现请求)

把movies.html放到src/main/resources/static目录下,内容示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>电影列表</title>
</head>
<body>
    <h1>热门电影</h1>
    <div id="movieList"></div>

    <script>
        // 页面加载完成后调用接口获取数据
        window.onload = function() {
            // 调用getMovies对应的接口
            fetch('/api/movies')
                .then(response => response.json())
                .then(movies => {
                    const listContainer = document.getElementById('movieList');
                    // 遍历数据渲染到页面
                    movies.forEach(movie => {
                        const item = document.createElement('div');
                        item.style = "border:1px solid #eee; margin:10px 0; padding:10px;";
                        item.innerHTML = `
                            <h3>${movie.title}</h3>
                            <p>上映日期:${movie.releaseDate}</p>
                            <p>评分:${movie.rating}</p>
                        `;
                        listContainer.appendChild(item);
                    })
                })
        }
    </script>
</body>
</html>

启动项目后访问/movies路径,页面会自动请求/api/movies接口获取数据并渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:45:03