SpringBoot 整合模板引擎、普通HTML


 

常用的模板引擎有2个

  • thymeleaf:springboot官方推荐使用的一款模板引擎,文件后缀是.html,直接新建html文件即可。thymeleaf前端显示、后端接口可以同时开发、自测,更适合前后端分离的项目。thymeleaf使用简单,但性能要差一些。
  • freemarker:一款通用的生成文本文件的模板引擎,可以生成html、xml、txt、md、代码源文件等各类文本文件,比如 mybatis plus generator 就使用 freemarker 作为代码生成器。freemarker在服务端渲染,通常由服务端编写,文件后缀是 .ftl 或 .ftlh,如果要作为html网页文件,可以在 /resources/templates 下新建html文件,把后缀改为 .ftl 。

 

springboot整合thymeleaf

pom.xml

创建项目时勾选 Template Engines -> Thymeleaf,也可以手动添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 

yml
spring:
  thymeleaf:
    #是否缓存页面,默认true,开发时用false,正式环境改为true
    cache: false
    #页面前缀,默认 classpath:/templates/
    prefix: classpath:/templates/
    #页面后缀,默认 .html
    suffix: .html

前缀、后缀一般不用配置,使用默认的即可

 

thymeleaf语法

使用${ }取后台传递的数据
 

1、th:text  显示普通文本

<!-- 常量 -->
<p th:text="hello"></p>

<!-- "hello"会覆盖原来的内容"你好" -->
<p th:text="hello">你好</p>

<!-- 标签体中没有内容时,可以写成单标签 -->
<p th:text="hello" />


<!-- 可以进行数学运算 -->
<!-- 3 -->
<p th:text="1+2"></p>
<!-- 1+2=3 -->
<p th:text="'1+2=' + (1+2)"></p>


<!-- 可以进行三元运算 -->
<p th:text="${user.age}>=18 ? 已成年 : 未成年"></p>


<!-- OGNL表达式${}可以取出controller传递的数据 -->
<!-- 使用点号取属性值时,底层是调用getter方法 -->
<p th:text="'用户名:' + ${user.username}"></p>


<!-- OGNL表达式${}中可以调用方法 -->
<p th:text="'用户名:' + ${user.getUsername()}"></p>
<p th:text="'转换为全大写:' + ${user.username.toUpperCase()}"></p>


<!-- 用'xxx'+'xxx'这种方式拼接字符串很麻烦,Thymeleaf简化了字符串拼接,字符串放在| |中即可  -->
<p th:text="|用户名:${user.username}|"></p>

 

2、th:utext  在th:text的基础上,可以解析html标签

//controller传递带有html标签字符串
model.addAttribute("msg", "<h2>user</h2>");
<!-- th:text会把标签作为普通字符串处理,不解析 -->
<p th:text="${msg}"></p>

<!-- th:utext会解析里面的标签 -->
<p th:utext="${msg}"></p>

 

3、th:object  处理对象

比如说controller传了一个user对象,在html中要多处使用user对象,${user.xxx},每次都要写user,很麻烦,可以这样

<!-- th:object用${}直接取对象 -->
<div th:object="${user}">
    <!-- 后续用*{}来操作,把$换成*,省略对象名 -->
    <p th:text="'用户名:'+*{username}"></p>
    <p th:text="'年龄:'+*{age}"></p>
    <p th:text="'手机号:'+*{tel}"></p>
    <p th:text="'住址:'+*{address}"></p>
</div>

 

4、th:src、th:href、th:action  分别相当于html的src、href、action

thymeleaf写法的路径要放在@{ }中

<link href="css/a.css" type="text/css" rel="stylesheet" />
<link th:href="@{css/a.css}" type="text/css" rel="stylesheet" />

<script src="js/vue.js"></script>
<script th:src="@{js/vue.js}"></script>

<img src="img/mac_pro.png" />
<img th:src="@{img/mac_pro.png}" />

<!-- 访问controller -->
<a href="/user">访问静态页面</a>
<a th:href="@{/user}">访问controller方法</a>

<form action="/login"></form>
<form th:action="@{/login}"></form>

 

5、thymeleaf常用的内置对象

内置对象说明
#requsetHttpServletRequest对象
#responseHttpServletReponse对象
#sessionHttpSession对象
#servletContextHttpServletContext对象
<!-- 可访问内置对象的属性、方法,在${}中使用,末尾不能加分号 -->
<p th:text="'用户名:' + ${#request.getParameter('username')}"></p>

 

6、th:if  条件判断

<!-- 条件为true才显示此元素,为false则不显示。符号可以用英文字母表示 -->
<p th:if="3>2">3>2</p>
<p th:if="3 gt 2">3 gt 2</p>


<!-- 与、或只能用and、or,不能用&&、|| -->
<p th:if="2>1 and 3>2">2>1 and 3>2</p>

<!-- 非可以用!或者not-->
<p th:if="! false">! false</p>
<p th:if="not false">not false</p>
符号英文描述

| gt | 即greater than
< | lt | 即less than
= | ge | 即greater equals
<= | le | 即less equals
== | eq | 即equals
!= | ne | 即not equals

 

7、th:each  迭代Array、List、Map

// controller传给html的数据
// Array
String[] arr = {"苹果", "李子", "梨子"};
model.addAttribute("arr", arr);

// List
ArrayList<String> list = new ArrayList<>();
list.add("语文");
list.add("数学");
list.add("英语");
model.addAttribute("list", list);

// Map
HashMap<String,Double> map = new HashMap<>();
map.put("香蕉", 4.0);
map.put("菠萝", 5.0);
map.put("芒果", 6.0);
model.addAttribute("map", map);
<!-- Array、List用法相同,ele代表一个元素 -->
<table>
    <tr th:each="ele:${arr}">
        <td th:text="${ele}"></td>
    </tr>
</table>


<!-- Map -->
<table>
	<!-- Map,entity代表一个键值对 -->
    <tr th:each="entity:${map}">
        <!--key、value是关键字,不能任意取 -->
        <td th:text="${entity.key}"></td>
        <td th:text="${entity.value}"></td>
    </tr>
</table>


<!-- Array、List、Map都可以再有一个临时变量,第一临时变量表示一个元素,第二个临时变量表示当前迭代元素的信息 -->
<table>
    <tr th:each="entity,status:${map}">
        <td th:text="${entity}"></td>
        <td th:text="${status}"></td>
    </tr>
</table>

第二个临时变量是对象,包含以下属性

  • index|count 当前元素是迭代的第几个元素,index从0开始,count从1开始
  • size 总的元素个数
  • odd|even 是否第奇|偶数个元素,布尔值。odd是奇,even是偶,跟字符数一致
  • first|last 是否是第一个|最后一个元素,布尔值

 

8、th:switch 、th:case  相当于java的switch语句

<!-- 只显示匹配的元素 -->
<div th:switch="${role}">
    <p th:case="common">普通用户</p>
    <p th:case="manager">vip</p>
    <p th:case="svip">svip</p>
    <!-- *相当于default -->
    <p th:case="*">其它</p>
</div>

 

9、th:include、th:include、th:replace  页面引入

1、引入整个页面

eg. 引入header.html、footer.html

<div th:include="@{footer.html}"></div>
<div th:insert="@{footer.html}"></div>
<div th:replace="@{footer.html}"></div>

<!-- 可以省略后缀 -->
<div th:include="@{footer}"></div>
<div th:insert="@{footer}"></div>
<div th:replace="@{footer}"></div>

th:include、th:insert 是把内容、效果包含进来,官方建议用 th:insert 代替 th:include ,th:replace是用包含页面的代码替换当前标签。

 

2、只引入页面的一部分

eg. 只引入header.html的nav部分

<!-- th:fragment给片段起一个名字 -->
<div th:fragment="nav">
    
</div>
<!-- 带不带后缀都行 -->
<div th:include="header :: nav"></div>
<div th:insert="header :: nav"></div>
<div th:replace="header :: nav"></div>

如果引用的是本页面中的片段,可以缺省页面,直接写成 ::片段;

可以把这些公共片段都放到一个单独的html文件中

 

3、向被包含的部分传递参数

<div th:fragment="nav(name,age)">
    <p th:text="${name}"></p>
    <p th:text="${age}"></p>
</div>
<div th:include="header :: nav('chy',20)"></div>
<div th:insert="header :: nav('chy',20)"></div>
<div th:replace="header :: nav('chy',20)"></div>

 

10、th:remove  移除元素

经常需要自动移除元素,比如controller从数据库查询商品,把商品信息传递给html展示出来,有时候没有满足条件的商品,传递的是null,这时候光秃秃地显示一个表头是不合适的,数据为空时应该自动移除表格|表头,给出提示。

<!-- 有数据就什么都不移除(显示table),没数据就移除整个table -->
<table th:remove="${goods_list}?none:all">
    
</table>

th:remove常用的值

  • all 移除整个元素
  • none 不移除什么(显示整个元素)
  • body 只移除body。<xxx>、</xxx>之间的东西叫做body,移除body后,<xxx>是空壳的
  • all-but-first 移除所有子元素,只保留第一个子元素

 

springboot整合freemarker

pom.xml

创建项目时勾选 Template Engines -> FreeMarker,或者手动添加依赖

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

 

yml
spring:
  freemarker:
    cache: false
    # 模板的加载位置,默认 classpath:/templates/
    template-loader-path: classpath:/templates/
    #前缀,默认 空串
    prefix:
    #后缀,低版本默认是.ftl,高版本默认是.ftlh
    suffix: .ftlh

一般不用设置 template-loader-path、prefix,使用默认的即可。

 

springboot整合普通html

在 resources/static 下新建page文件夹用于存放html文件。
 

yml
spring:
  mvc:
    view:
      prefix: /page/
      suffix: .html

注意普通html的 prefix 不是以 classpath: 开头的,模板引擎和 jsp 都可以使用 ${ }之类的表达式语言直接取controller传递的数据,都是由后端进行渲染,普通html则是由浏览器渲染。
 

页面路由配置
@Controller
public class PageController {

    @RequestMapping("{pageName}.html")
    public String page(@PathVariable String pageName) {
        return pageName;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值