从Spring官网获取SpringBoot项目的时候,就已经看见了static与templates文件夹,这两个文件夹是用来放静态资源的。什么HTML,images,css外部文件等等,都放在这了,而SpringBoot推荐使用thymeleaf,这篇文章记录一下
static就像webapp文件夹一样,默认127.0.0.1:8080/… 就是访问这里,同时也可以新建resource或者public文件夹,与static一样,都可以默认访问,但是SpringBoot不提倡这样,所以我们最好还是static…
这里说一下webjars这个概念,SpringBoot可以在pom.xml中导入jquery,Bootstrap等这些前端框架,导入之后引用即可,后续补上html引用这种jar包形式的文件方法
templates默认是受保护的。什么是受保护呢,意思就是跟WEB-INF一样,直接是无法访问的。需要由视图解析器跳转访问。说到这个文件就要温馨提示一波,它不推荐使用jsp,但是想用也是可以的。
可以参考这里:https://blog.csdn.net/weixin_43818387/article/details/88404679
言归正传,这个文件夹通常放一些html页面,通过thymeleaf跳转进行访问
thymeleaf怎么用呢?
首先,加入依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
导入一个命名空间,使其变为模板
<html lang="en" xmlns:th="http://www.thymeleaf.org">
然后使用th标签进行操作,例如
<span th:text="${hello}"></span>
则会从后台返回的Model中获取hello属性并注入
thymeleaf可以一次获取多个字符串
${hello+hi+hey}这种格式,中间可以穿插字符串,例如" "这样
其中还可以调用java代码,例如${date.gettime()}这样
其还自带了一些库,封装了些方法,例如#strings,#arrays,#lists等
<span th:text="${#strings.isEmpty('fucyou')}"/>
<span th:text="${#lists.size(list)}"/>
它也可以访问Http内置对象,只要在控制层加入Http接口,set入内容,前台可以通过${session.(属性)}来进行访问
<span th:text="${session.congcong}"/>
可以利用object属性进行访问上级,下级只需要*{(属性名)}即可进行读取
<table th:object="${login}">
<span th:text="*{username}"></span>
<span th:text="*{password}"></span>
</table>
路径最好使用@{/(路径)}
因为如果有设置server.servlet.context-path=/tx这样的通过项目名访问
相对路径会无法访问,而@{}可以绝对路径进行访问。免除了需要更改的步骤
类似这样
<img style="width: 100px;height: 180px" th:src="@{/images/aersasi.jpg}"/>
也可以利用其来进行路径拼接,例如
<a th:href="@{/test(username='zhexue',password='zhanshi')}">link</a>
这样就等效/test?uername=zhexue&password=zhanshi
一样避免了项目名路径问题
他也可以利用${}进行赋值
例如
<a th:href="@{/test(username='zhexue',password=${p.passwor})}">link</a>
常量,运算,if,三元运算符等,与正常语法基本一致
th:text="${1>2?1:2}" <span th:if="1+1>1">boynextstroe</span>
循环则是th:each
<table th:each="p : ${lists}">
<td th:text="${p.text}"></td>
......
如果想要索引,计数什么的,可以加入多一个遍历属性,随意命名,例如item
<table th:each="p,item : ${list}">
<td th:text="${item.index}"/>
<td th:text="${p.toString()}"></td>
</table>
item有各种属性,例如index,odd等,可以利用这些属性结合使用。
比如给奇数添加类
<th:class="item.odd? 'odd'"/>
欢迎各路大神指点。。