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>