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

Spring Boot项目中前端如何对接后端Dummy数据接口?

问题解决步骤

后端核心问题修复

你的HomeController用了@Controller注解,Spring默认会把返回值当作视图名称去查找页面,而不是把JSONArray序列化为JSON响应返回给前端。这是导致前端拿不到数据的主要原因,需要做以下修改:

方案1:替换为@RestController

直接把@Controller改成@RestController,它会自动给所有方法添加@ResponseBody,让返回的对象直接转为JSON:

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONParser;
import java.io.*;

@RestController // 替换原有的@Controller
public class HomeController {

    @GetMapping("/api/dummy")
    public JSONArray getData() throws IOException, ParseException {
        JSONParser parser = new JSONParser();
        // 使用ClassPathResource读取资源,适配jar包打包后的环境(避免FileReader找不到路径)
        ClassPathResource resource = new ClassPathResource("dummy/dummy.json");
        try (Reader reader = new InputStreamReader(resource.getInputStream())) {
            JSONObject jsonObject = (JSONObject) parser.parse(reader);
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            return jsonArray;
        }
    }
}

方案2:保留@Controller,添加@ResponseBody

如果不想修改类注解,就在getData方法上加上@ResponseBody:

@Controller
public class HomeController {

    @GetMapping("/api/dummy")
    @ResponseBody // 新增此注解,告诉Spring返回JSON而非视图
    public JSONArray getData() throws IOException, ParseException {
        // 读取代码同上
    }
}

前端排查与优化

后端修复后,再针对前端代码做调试和优化:

  1. 先验证接口可用性
    直接在浏览器地址栏访问http://localhost:8080/api/dummy(替换成你的应用端口),确认能看到正确的JSON结构,比如类似:

    [{"forum":[{"id":1,"title":"如何使用Spring Boot"},{"id":2,"title":"JPA入门"}]}]
    

    如果看不到,先解决后端的问题。

  2. 添加调试日志,确认数据结构
    修改前端代码,添加日志打印,排查数据是否正确:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $.ajax({
                type: "GET",
                url: "/api/dummy",
                dataType: "json", // 指定接收JSON类型,避免解析错误
                success: function(response) {
                    console.log("接口返回数据:", response);
                    // 检查数据结构是否符合预期
                    if (!response[0] || !response[0].forum) {
                        console.error("数据结构错误:未找到forum数组");
                        return;
                    }
                    const forumData = response[0].forum;
                    const forumListElement = $("#forumList");
                    forumListElement.empty(); // 清空原有内容,避免重复加载
                    forumData.forEach(forum => {
                        console.log("当前帖子:", forum);
                        forumListElement.append(`<li><a href='/question/${forum.id}'>${forum.title}</a></li>`);
                    });
                },
                error: function(xhr, status, error) {
                    console.error("请求失败:", status, error);
                    console.error("状态码:", xhr.status);
                    console.error("响应内容:", xhr.responseText);
                }
            });
        });
    </script>
    
  3. 确认页面元素存在
    确保你的HTML页面中有id="forumList"的元素,比如:

    <ul id="forumList"></ul>
    

额外注意事项

  • dummy.json的路径必须是src/main/resources/dummy/dummy.json,确保文件存在且格式正确(用JSON校验工具检查是否有语法错误)。
  • 异常处理:后端方法直接抛出异常会导致前端收到500错误,建议添加全局异常处理或者在方法内捕获异常,返回友好的错误信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:07:45