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

SpringBoot+Thymeleaf后端调用时cart.html页面不显示,仅返回字符串

问题分析与解决方案

核心问题:@ResponseBody 注解导致视图不渲染

你的控制器方法上添加了@ResponseBody注解,这个注解会将方法返回值直接作为HTTP响应体返回给客户端,而非让Spring MVC把返回的字符串当作视图名称去匹配模板文件。因此浏览器只会收到字符串"cart",不会渲染对应的cart.html页面。

修复步骤

1. 移除控制器方法上的@ResponseBody注解

修改后的控制器代码:

@GetMapping("/cart")
public String getIfBorrowedBook(Model model, @RequestParam List<Integer> bookIds) {
    System.out.println(bookIds);
    List<Books> booksInCart = new ArrayList<>();
    for(Integer id:bookIds) {
        booksInCart.add(booksService.findById(id));
    }
    System.out.println(booksInCart);
    model.addAttribute("booksInCart", booksInCart);
    return "cart";
}

2. 修正前端表单提交逻辑

表单中的提交按钮被<a href="cart">包裹,点击时会优先触发a标签的跳转,而非表单提交动作,导致bookIds参数无法正确传递。移除a标签,直接使用button提交:

<div>
    <button type="submit" class="btn btn-primary">Add to Cart</button>
</div>

3. 确认Thymeleaf依赖已正确引入

确保项目依赖中包含Spring Boot Thymeleaf Starter:

Maven 依赖:

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

Gradle 依赖:

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

验证要点

  • cart.html必须位于src/main/resources/templates目录,这是Spring Boot默认的Thymeleaf模板存放路径
  • 确认booksService.findById(id)能正确返回Books对象,且对象的title、genre、author、edition属性有有效值
  • 提交表单后,浏览器地址栏应显示类似/cart?bookIds=1&bookIds=2的参数,说明bookIds列表已正确传递

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:20:14