有如下代码: JSONArray ds = (JSONArray) json.get("DS"); 其中ds的值是[{"Station_Name":"耿马国家基本气象站","Station_Id_C":"56946","SUM_PRE_Time_2020":"166"}, {"Station_Name":"临沧国家基本气象站","Station_Id_C":"56951","SUM_PRE_Time_2020":"95.4"}, {"Station_Name":"沧源","Station_Id_C":"56944","SUM_PRE_Time_2020":"260.8"}, {"Station_Name":"双江","Station_Id_C":"56950","SUM_PRE_Time_2020":"70.4"}] 如何结合freemarker动态生成html.将里面对应的Station_Id_C,SUM_PRE_Time_2020的值展示成一张表格 其中springboot该怎么写
时间: 2023-03-03 07:42:28 浏览: 112
JSON(net.sf.json.JSONArray)需要的jar包
你可以使用Freemarker模板引擎和Spring Boot框架来动态生成HTML表格,具体实现步骤如下:
1. 首先,将JSON数组转换为Java List对象,可以使用阿里巴巴的fastjson库进行转换:
```java
JSONArray ds = (JSONArray) json.get("DS");
List<Map<String, String>> stationList = JSONObject.parseObject(ds.toJSONString(), new TypeReference<List<Map<String, String>>>(){});
```
2. 然后,在Spring Boot项目中创建一个Controller类,将List对象传递给Freemarker模板:
```java
@Controller
public class StationController {
@RequestMapping("/station")
public String showStationList(Model model) {
JSONArray ds = (JSONArray) json.get("DS");
List<Map<String, String>> stationList = JSONObject.parseObject(ds.toJSONString(), new TypeReference<List<Map<String, String>>>(){});
model.addAttribute("stationList", stationList);
return "station-list";
}
}
```
3. 创建Freemarker模板station-list.ftl,并在其中使用Freemarker的语法生成HTML表格:
```html
<table>
<thead>
<tr>
<th>站点名称</th>
<th>站点ID</th>
<th>降水量</th>
</tr>
</thead>
<tbody>
<#list stationList as station>
<tr>
<td>${station.Station_Name}</td>
<td>${station.Station_Id_C}</td>
<td>${station.SUM_PRE_Time_2020}</td>
</tr>
</#list>
</tbody>
</table>
```
4. 最后,在Spring Boot项目中配置Freemarker视图解析器:
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public ViewResolver getViewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setPrefix("");
resolver.setSuffix(".ftl");
resolver.setCache(false);
resolver.setContentType("text/html; charset=utf-8");
return resolver;
}
@Bean
public FreeMarkerConfigurer getFreeMarkerConfigurer() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/WEB-INF/views/");
configurer.setDefaultEncoding("UTF-8");
return configurer;
}
}
```
这样,当访问“/station”路径时,Spring Boot将会渲染station-list.ftl模板,动态生成HTML表格,并将结果返回给客户端。
阅读全文