今天学习了springboot的两大常用模版:thymeleaf和freemarker
Thymeleaf的优点:它就是html页面。下面直接上代码
使用步骤:
1.新建modul时勾选Thymeleaf,自动添加相关pom依赖 (我就thymeleaf,freemarker一起用了,不会冲突)
2.配置application.yml文件
Spring Boot官方文档建议在开发时将缓存关闭,那就在application.yml文件中加入下面这行
spring.thymeleaf.cache=false
正式环境还是要将缓存开启的
server:
servlet:
context-path: /springboot02
spring:
thymeleaf:
cache: false #项目开发完后改为true
3.html开发的相关指令
页面加上: 自动提示
例子:user/list.html
用户列表
th:text 用于展示
th:each 循环
id
姓名
密码
传值
controller
// ----------------------------------thymeleaf---------------------------------------------------
@RequestMapping("/user/list")
public ModelAndView userlsit(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("user/list");
modelAndView.addObject("title","用户列表");
List list=new ArrayList<>();
list.add(new UserEntity(1,"张翊晗","918"));
list.add(new UserEntity(2,"张翊栩","515"));
modelAndView.addObject("users",list);
return modelAndView;
}
效果 :
1.导入pom依赖 ( 新建时有了)
2.配置application.yml文件
application.yml文件的默认配置
spring:
freemarker:
# 设置模板后缀名
suffix: .ftl
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
# 设置ftl文件路径,默认是/templates,为演示效果添加role
template-loader-path: classpath:/templates/role
mvc:
static-path-pattern: /static/**
3.配置 .ftl的界面
Settings--->Editor-->File and Code Templates
extension:ftl 跟application.yml 中的模版后缀名要一致
4.标页面签的使用
list.ftl页面
Title
<#include 'comment.ftl'>
取值(${name!'暂无'} 表示name值是''时,默认值暂无 ,值不可为null否则报错)
[${name!'暂无'}] ,welcome to page
非空判断
<#if name?exists>
存在的
#if>
条件表达式
<#if sex='女'>
女士
<#elseif sex='男'>
男士
<#else>
保密
#if>
循环
id
姓名
密码
<#list users as u>
${u.uid}
${u.uname}
${u.pwd}
#list>
include
<#include 'foot.ftl'>
变量的设置(局部变量:当前页面 全局变量:整个工程)
<#-- 相当于 -->
<#--局部变量-->
<#assign ctx1>
${springMacroRequestContext.contextPath}
#assign>
<#--全局变量-->
<#global ctx2>
${springMacroRequestContext.contextPath}
#global>
${ctx1},${ctx2}
controller
//--------------------------------freemarker--------------------------------------------------
@RequestMapping("/role/list")
public ModelAndView rolelsit(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("list");
modelAndView.addObject("name",null);
modelAndView.addObject("sex","女");
List list=new ArrayList<>();
list.add(new UserEntity(1,"张翊晗","918"));
list.add(new UserEntity(2,"张翊栩","515"));
modelAndView.addObject("users",list);
return modelAndView;
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/role1/list")
public ModelAndView rolelist1(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("xx");
return modelAndView;
}
foot.ftl
登录1
登录2
login.ftl
Title
登录成功
<#assign ctx>
${springMacroRequestContext.contextPath}
#assign>
<#--base标签作用: static/js/test.js就等于${ctx}/static/js/test.js 默认前面加上${ctx}-->
test.js
function f() {
alert('test')
}
效果图