springboot thymeleaf 与 freemarker的简单使用
springboot不推荐使用jsp开发
那么企业的开发主要分为两种
1.thymeleaf模板(主要基于.html的开发)
页面拿值
<!--页面拿值-->
<h3 th:text="${name}"></h3>
页面取值
<!--页面取值-->
<select name="hobby">
<option th:each="user :${UserList}" th:text="${user.userName}" th:value="${user.id}"> </option>
</select>
页面遍历
<!--table表格的遍历-->
<table border="2" width="600px" th:height="20px" height="600px">
<thead>
<tr>
<td>Id</td>
<td>name</td>
<td>distribution</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr th:each="user :${UserList}">
<td th:text="${user.id}"></td>
<td th:text="${user.userName}"></td>
<td th:text="${user.distribution}"></td>
<td ><a href="" onclick="">删除</a></td>
</tr>
</tbody>
</table>
后台传值
@Controller
public class UserController {
@RequestMapping("/user/list")
public ModelAndView UserList(){
ModelAndView mv = new ModelAndView();
List list = new ArrayList();
list.add( new User("1","xiaowu","学生"));
list.add( new User("2","huxiaowu","老师"));
list.add( new User("3","dawu","经理"));
mv.addObject("UserList",list);
mv.addObject("name","小五");
mv.setViewName("/list");
return mv;
}
2.freemarker模板(主要基于.ftl的开发)
使用
1.在application.yml文件默认配置
server:
servlet:
context-path: /springboot
spring:
thymeleaf:
cache: false
freemarker:
# 设置模板后缀名
suffix: .ftl
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
# 设置ftl文件路径,默认是/templates,为演示效果添加role
template-loader-path: classpath:/templates
2.页面拿值 ,取值,遍历,全局变量,包含页面的使用
<h3>拿值</h3>
<#--如果前台传来null会报错 那么!表示如果为null的话替代为后面的值 也就是‘哈哈’-->
${role !'哈哈'}
<h3>if判断</h3>
<#--? exists 是否存在-->
<#if role ? exists>
存在
</#if>
<#if sex='boy'>
男
<#elseif sex='girl'>
女
<#else>
保密
</#if>
<h3>foreach遍历</h3>
<table border="2" width="600px" th:height="10px" height="300px">
<thead>
<tr>
<td>Id</td>
<td>name</td>
<td>distribution</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<#list RoleList as user>
<tr >
<td>${user.id}</td>
<td>${user.userName}</td>
<td>${user.distribution}</td>
<td><a href="" onclick="">删除</a></td>
</tr>
</#list>
</tbody>
</table>
<h3>包含页面</h3>
<#include 'include.ftl'/>
<h3>局部变量(assign)/全局变量(global)</h3>
<#assign ctx1>
${springMacroRequestContext.contextPath}
</#assign>
<#global ctx2>
${springMacroRequestContext.contextPath}
</#global>
${ctx1}和${ctx2}
应用
在Idea中没有创建freemarker的程序 可以自己创建与HTML一样的简单程序
1.进入IDEA的setting
2.添加
这时候就有应用了