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

使用JavaScript从@RestController获取JSON数据时页面加载与数据异常排查

问题描述

访问指定URL时HTML页面无法加载,同时无法从@RestController获取JSON格式数据。已确认URL正确,ReservationController代码逻辑无明显问题,HTML与JavaScript文件存放于templates目录,控制器位于src/java/package目录下。

问题现象

访问api/reservations/all时无正常JSON返回

Controller代码

@RestController
@RequestMapping("api/reservations")
public class ReservationController {

    private final ReservationService reservationService;

    @Autowired
    public ReservationController(ReservationService reservationService) {
        this.reservationService = reservationService;
    }
    
    @GetMapping("/all")
    public List<Reservation> showAllReservations() throws SQLException {
        return reservationService.showAllReservations();
    }
}

HTML + JavaScript代码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Reservations</title>
  </head>
  <body>
    <script>
      // Fetch JSON data from REST controller
      fetch("http://localhost:8080/api/reservations/all")
        .then((response) => response.json())
        .then((data) => {
          // Iterate over each object in the JSON array
          var formattedData = "";

          data.forEach((item) => {
            formattedData +=
              "<p>Reservation ID: " +
              item.id +
              "</p>" +
              "<p>Customer: " +
              item.customer.name +
              "</p>" +
              "<p>Email: " +
              item.customer.email +
              "</p>" +
              "<p>Check-in Date: " +
              item.dateCheckIn +
              "</p>" +
              "<p>Check-out Date: " +
              item.dateCheckOut +
              "</p>" +
              "<hr>";
          });
          // Update the HTML container with the formatted data
          var dataContainer = document.getElementById("data-container");
          dataContainer.innerHTML = formattedData;
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    </script>
    <div id="data-container"></div>
  </body>
</html>
排查与解决方案

1. 配置HTML页面的访问路由

Spring Boot默认templates目录下的HTML无法直接通过URL访问,需添加@Controller映射页面:

@Controller
public class PageController {
    @GetMapping("/reservations")
    public String showReservationsPage() {
        return "reservations"; // 对应templates目录下的HTML文件名(不含后缀)
    }
}

之后通过http://localhost:8080/reservations访问HTML页面。

2. 解决跨域限制

如果直接打开本地HTML文件(file://协议)调用localhost:8080的API,会触发浏览器跨域拦截,两种解决方式:

  • 给ReservationController添加跨域注解(开发环境临时使用):
@RestController
@RequestMapping("api/reservations")
@CrossOrigin(origins = "*")
public class ReservationController {
    // 原有代码不变
}
  • 将HTML文件移至static目录,通过http://localhost:8080/reservations.html访问,同域下无跨域问题。

3. 排查API接口异常

  • 查看项目控制台日志,确认reservationService.showAllReservations()是否抛出SQLException或其他异常,导致接口返回500错误;
  • 用Postman或curl直接调用API,检查返回状态码:
curl http://localhost:8080/api/reservations/all

若返回404,检查是否配置了server.servlet.context-path前缀,导致实际API路径不符;若返回500,排查数据库连接或Service层逻辑。

4. 确保实体类可正常序列化JSON

Reservation和Customer实体类需满足:

  • 提供所有属性的getter方法(Jackson默认通过getter序列化);
  • 存在循环引用时,添加@JsonIgnore或@JsonManagedReference/@JsonBackReference注解处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:29:54