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

Spring Boot控制器返回数据至HTML及业务分层问题求助

问题1:Chart.js无法展示Controller返回的计算结果

解决步骤

  • 确保Controller返回JSON格式数据
    为Controller方法添加@ResponseBody注解,或直接用@RestController替代@Controller,将计算结果封装为实体类后直接返回:
    @PostMapping("/simulate")
    @ResponseBody
    public EpidemicResult simulate(@RequestParam int population, @RequestParam double infectionRate) {
        // 原计算逻辑生成模拟数据
        List<Integer> infectedList = new ArrayList<>();
        // ... 计算过程
        return new EpidemicResult(infectedList);
    }
    
  • 前端用异步请求获取数据
    避免使用普通form提交(会刷新页面),用fetch或AJAX发送请求,接收JSON后更新Chart.js数据集:
    document.querySelector('#submit-btn').addEventListener('click', () => {
        const population = document.querySelector('#population').value;
        const infectionRate = document.querySelector('#infection-rate').value;
    
        fetch('/simulate', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `population=${population}&infectionRate=${infectionRate}`
        })
        .then(res => res.json())
        .then(data => {
            // 更新已有图表数据
            const chart = Chart.getChart('epidemic-chart');
            chart.data.datasets[0].data = data.infectedList;
            chart.update();
        });
    });
    
  • 初始化Chart.js空实例
    提前创建图表框架,预留空数据位置,后续仅更新数据集:
    const ctx = document.getElementById('epidemic-chart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: Array.from({length: 30}, (_, i) => `Day ${i+1}`),
            datasets: [{
                label: 'Infected Cases',
                data: [],
                borderColor: '#ff4444'
            }]
        }
    });
    
问题2:计算逻辑迁移至Service层

解决步骤

  • 定义Service接口
    明确业务方法的输入输出:
    public interface EpidemicSimulateService {
        EpidemicResult runSimulation(int population, double infectionRate);
    }
    
  • 实现Service接口
    将Controller中的计算逻辑完整迁移至Service实现类:
    @Service
    public class EpidemicSimulateServiceImpl implements EpidemicSimulateService {
        @Override
        public EpidemicResult runSimulation(int population, double infectionRate) {
            List<Integer> infectedList = new ArrayList<>();
            // 完整计算逻辑,比如SIR模型实现
            for (int day = 0; day < 30; day++) {
                // ... 每日感染人数计算
                infectedList.add(calculatedValue);
            }
            return new EpidemicResult(infectedList);
        }
    }
    
  • Controller注入Service并调用
    移除Controller内的计算代码,通过依赖注入调用Service方法:
    @Controller
    public class EpidemicController {
        private final EpidemicSimulateService simulateService;
    
        // 构造方法注入(Spring推荐方式)
        public EpidemicController(EpidemicSimulateService simulateService) {
            this.simulateService = simulateService;
        }
    
        @PostMapping("/simulate")
        @ResponseBody
        public EpidemicResult simulate(@RequestParam int population, @RequestParam double infectionRate) {
            return simulateService.runSimulation(population, infectionRate);
        }
    }
    
  • 关键注意事项
    • Service类需标注@Service注解,确保Spring能扫描并实例化Bean;
    • 若计算需依赖数据访问层(如Repository),直接在Service中注入即可,严格遵循分层架构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:52:23