Spring Boot开发实战——echarts图标填充数据
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/charts")
public class ChartController {
@Autowired
private DataService dataService;
@GetMapping("/pie")
public String getPieChartData(Model model) {
Map<String, Object> pieChartData = dataService.getPieChartData();
model.addAttribute("pieChartData", pieChartData);
return "pieChart";
}
@GetMapping("/line")
@ResponseBody
public Map<String, Object> getLineChartData() {
return dataService.getLineChartData();
}
}
@Service
class DataService {
public Map<String, Object> getPieChartData() {
Map<String, Object> pieChartData = new HashMap<>();
// 填充数据
pieChartData.put("title", "示例饼图");
pieChartData.put("legendData", Arrays.asList("A", "B", "C", "D"));
pieChartData.put("seriesData", Arrays.asList(10, 20, 30, 40));
return pieChartData;
}
public Map<String, Object> getLineChartData() {
Map<String, Object> lineChartData = new HashMap<>();
// 填充数据
lineChartData.put("title", "示例折线图");
lineChartData.put("legendData", Arrays.asList("E", "F", "G", "H"));
lineChartData.put("xAxisData", Arrays.asList(1, 2, 3, 4));
lineChartData.put("seriesData", Arrays.asList(50, 60, 70, 80));
return lineChartData;
}
}
在这个代码实例中,我们定义了一个DataService
类,它包含了获取饼图和折线图所需数据的方法。然后在ChartController
中,我们使用@Autowired
注解自动注入了DataService
的实例,并且定义了两个用于返回图表数据的GET请求。其中getPieChartData
方法将数据填充至Model中,然后返回一个视图名称,该视图对应于一个echarts图表模板。getLineChartData
方法直接返回了一个包含图表数据的Map对象,这个方法被标记为@ResponseBody
,意味着它将返回的数据直接作为HTTP响应的body部分,通常用于返回JSON格式的数据。
评论已关闭