freemarker整合springboot(一):简单页面渲染
简单页面渲染
freemarker做静态化有很多细节,有些是和业务相关的,有些是与技术的使用相关,比如分页的实现、国家化、前后端分离、自定义标签等,这里先介绍简单的页面渲染。
本地渲染(前后端在一个容器中)
maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
application.yml配置
spring:
freemarker:
template-loader-path:
- classpath:/templates
- file:./templates
cache: true
checkTemplateLocation: true
settings:
classic_compatible: true #处理空值
template_exception_handler: rethrow
template_update_delay: 0
datetime_format: yyyy-MM-dd HH:mm
number_format: 0.##
suffix: .ftl
页面模板
渲染
服务端
@Controller
@RequestMapping("user")
@Slf4j
public class UserController {
@Autowired
private Configuration configuration;
@RequestMapping("show.html")
public String user(ModelMap modelMap) {
PageVO page = new PageVO();
// 读取json数据
page.setContent(JsonUtil.readJsonFile("static/config/userList.json"));
// 将要渲染的数据放到modelMap
modelMap.addAttribute("page", page);
// 返回模板页面
return "/user/show";
}
}
页面
<tbody>
<#list page.content as row>
<tr>
<!-- 页面通过${}取数据,通过list,if等标签做逻辑判断等数据处理 -->
<td class="text-center">${row.id}</td>
<td>${row.username}</td>
<td>${row.name}</td>
<td>${row.email}</td>
<td>
<#list row.roles as role>
${role.name}
</#list>
</td>
<td>
<#if (row.status == 0)>
<span class="label label-success">启用</span>
<#else>
<span class="label label-default">禁用</span>
</#if>
</td>