多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] # 简介 spring boot项目只有src目录,没有webapp目录,会将静态访问(html/图片等)映射到其自动配置的静态目录,如下 ~~~ /static /public /resources /META-INF/resources ~~~ 比如,在resources建立一个static目录和index.htm静态文件,访问地址 [http://localhost:8080/index.html](http://localhost:8080/index.html) **配置** 动态页面需要先请求服务器,访问后台应用程序,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。 在pom.xml中添加Thymeleaf组件 ~~~ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ~~~ ~~~ #开启模板缓存(默认值:true) spring.thymeleaf.cache=false #Check that the template exists before rendering it. spring.thymeleaf.check-template=true #检查模板位置是否正确(默认值:true) spring.thymeleaf.check-template-location=true #Content-Type的值(默认值:text/html) spring.thymeleaf.servlet.content-type=text/html #开启MVC Thymeleaf视图解析(默认值:true) spring.thymeleaf.enabled=true #模板编码 spring.thymeleaf.encoding=UTF-8 #要被排除在解析之外的视图名称列表,用逗号分隔 spring.thymeleaf.excluded-view-names= #要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5) spring.thymeleaf.mode=HTML5 #在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/) spring.thymeleaf.prefix=classpath:/templates/ #在构建URL时添加到视图名称后的后缀(默认值:.html),控制器那return也要加 spring.thymeleaf.suffix=.html #Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。 spring.thymeleaf.template-resolver-order= #可解析的视图名称列表,用逗号分隔 spring.thymeleaf.view-names= ~~~ **控制器** 这边只能用`@Controller`这个注解 ~~~ import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class TemplatesController { @GetMapping("/abc") public String test(Model model) { //逻辑处理 model.addAttribute("say","欢迎欢迎,热烈欢迎"); return "index.html"; //配置了 spring.thymeleaf.suffix=.html } } ~~~ **页面** `spring.thymeleaf.prefix=classpath:/templates/` 这个路径下 注意标签: `xmlns:th="http://www.thymeleaf.org"` ~~~ <!DOCTYPE html> <html lang="zh-CN" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>第一个HTML页面</title> </head> <body> <div> <!--/*@thymesVar id="say" type="com.jdxia.consumer.web"*/--> <p th:text="${say}"></p> </div> </body> </html> ~~~ # js读取 **script标签中 th:inline 一定不能少** ~~~ <script th:inline="javascript" type="text/javascript"> var message = [[${say}]]; console.log(message); </script> ~~~ # 常用标签 ~~~javascript 关键字   功能介绍     案例 th:id   替换id      <input th:id="'xxx' + ${collect.id}"/> th:text  文本替换     <p th:text="${collect.description}">description</p> th:utext 支持html的文本替换 <p th:utext="${htmlcontent}">conten</p> th:object 替换对象     <div th:object="${session.user}"> th:value 属性赋值     <input th:value="${user.name}" /> th:with 变量赋值运算     <div th:with="isEven=${prodStat.count}%2==0"></div> th:style 设置样式         th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" th:onclick 点击事件       th:onclick="'getCollect()'" th:each 属性赋值         tr th:each="user,userStat:${users}"> th:if 判断条件         <a th:if="${userId == collect.userId}" > th:unless 和th:if判断相反     <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> th:href 链接地址           <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> /> th:switch 多路选择 配合th:case 使用 <div th:switch="${user.role}"> th:case th:switch的一个分支     <p th:case="'admin'">User is an administrator</p> th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment="alert"> th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> /> th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div> th:selected selected选择框 选中 th:selected="(${xxx.id} == ${configObj.dd})" th:src 图片类地址引入       <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" /> th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript"> th:action 表单提交的地址     <form action="subscribe.html" th:action="@{/subscribe}"> th:remove 删除某个属性     <tr th:remove="all">                     1.all:删除包含标签和所有的孩子。                     2.body:不包含标记删除,但删除其所有的孩子。                     3.tag:包含标记的删除,但不删除它的孩子。                     4.all-but-first:删除所有包含标签的孩子,除了第一个。                     5.none:什么也不做。这个值是有用的动态评估。 th:attr 设置标签属性,多个属性可以用逗号分隔 比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。 ~~~ ## th:text 可对表达式或变量求值,并将结果显示在其被包含的 html 标签体内替换原有html文本。 文本链接: 用 "+" 符号,若是变量表达式也可以用“|”符号 ~~~javascript <p th:text="#{home.welcome}">Welcome to our grocery store!</p> ~~~ 局限:只能在html5中使用 ~~~javascript <p data-th-text="#{home.welcome}">Welcome to our grocery store!</p> ~~~ `th:text`属性,他声明设置表达式的值,并使表达式返回的值来填充标签内容,替换或设置标签内部的内容 `#{home.welcome}`表达式,一个标准的表达式语法,指出在模板中,th:text属性所对应Message的key,即使用home.welcome对应的value替换现有内容 ## `th:utext`(非转义文本:`unescaped text`) (想要输出转义字符效果) ~~~javascript home.welcome=Welcome to our <b>fantastic</b> grocery store! ~~~ 执行此模板,默认使用来解析,结果为: ~~~javascript <p>Welcome to our &lt;b&gt;fantastic&lt;/b&gt; grocery store!</p> ~~~ 解决方案 ~~~javascript <p th:utext="#{home.welcome}">Welcome to our grocery store!</p> ~~~ 等效于html:`Welcome to our fantastic grocery store!` ## th:href链接 `@{xxx}` :链接url的表达式 ~~~javascript <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a> ~~~ # 页面取值 **循环取值:** ~~~ <tr th:each="list,stat : ${accountList}"> <td th:text="${stat.count}"></td> //序号,1,2,3,4,5 <td th:text="${list.account}"></td> <td th:text="${list.name}"></td> <td th:text="${list.password}"></td> <td th:text="${list.accountType}"></td> <td th:text="${list.tel}"></td> </tr> ~~~ **循环中状态,男女,为0,1时,改为中文** status为0,1时 ~~~ <td th:switch="${status}"> <span th:case="0">否</span> <span th:case="1">是</span> </td> ~~~ ## if条件判断 Thymeleaf 中使⽤用 th:if 和 th:unless 属性进⾏行行条件判断,在下⾯面的例例⼦子中, `<a>` 标签只有在 th:if 中条件成立时才显示: ~~~ <a th:if="${flag == 'yes'}" th:href="@{http://favorites.ren/}"> home </a> <a th:unless="${flag != 'no'}" th:href="@{http://www.ityouknow.com/}" >ityouknow</ a> ~~~ `th:unless` 与 `th:if` 恰好相反,只有表达式中的条件不成立,才会显示其内容 ## for循环 ~~~ <h1>for 循环</h1> <table> <tr th:each="user,iterStat : ${users}"> <td th:text="${user.name}">neo</td> <td th:text="${user.age}">6</td> <td th:text="${user.pass}">213</td> <td th:text="${iterStat.index}">index</td> </tr> </table> ~~~ iterStat 称作状态变量量,属性有: * index,当前迭代对象的 index(从 0 开始计算); * count,当前迭代对象的 index(从 1 开始计算); * size,被迭代对象的⼤大⼩小; * current,当前迭代变量量; * even/odd,布尔值,当前循环是否是偶数/奇数(从 0 开始计算); * first,布尔值,当前循环是否是第⼀一个; * last, 布尔值,当前循环是否是最后一个 ## 一般字符串取值 ~~~ <td th:text="${list.account}"></td> <td>[[${list.account}]]</td> <span th:text="${name}></span> <span>[[${name}]]</span> ~~~ ## 标签属性取值 input标签的value值,id取值,属性取值前面都加th: ~~~ <input type="text" name="adminname" th:value="${adminname}" th:id="${id}"> ~~~ ## 标签循环 标签循环,以及循环选中,标签属性取值 ~~~ <ul> <li id="rolehtml"> <span th:each="list:${rolelist}"><input type="checkbox" th:checked="${list.remark1 eq 'checked'}" name="menuId" th:data-id="${list.id}" th:id="${list.id}" th:value="${list.id}" ><label th:for="${list.id}" th:text="${list.rolename}" class="qx-lable">值111</lable></span> </li> </ul> ~~~ ~~~ <select name="compId" id="compId"> <option th:each="list:${listc}" th:value="${list.compId}" th:selected="${admin.compId eq list.compId}" th:text="${list.compName }"></option> </select> ~~~ ## select选中标签 循环选中参考上面 ~~~ <select class="form-control" id="flag" name="flag"> <option value="0" th:selected="${admin.flag==0}">否</option> <option value="1" th:selected="${admin.flag==1}">是</option> </select> ~~~ ## js取值 ~~~ <script type="text/javascript"> var num = [[${num}]]; <script> ~~~ ## 字符串处理 **替换金额最后的.0** ~~~ <td th:text="${#strings.replace(user.loanmoney,'.0','')}">金额(万元)</td> <td >[[${#strings.replace(user.loanmoney,'.0','')}]] 金额(万元)</td> ~~~ **截取字符串** 将电话号码18360554400显示为183\*\*\*\*4400 ~~~ <td>[[${#strings.substring(userphone,0,3)}]]<span>****</span>[[${#strings.substring(userphone,7,11)}]] </td> ~~~ **if判断** ~~~ <tr th:if="${pageInfoSize eq 0}"> <td colspan="12">没有查询相关记录</td> </tr> ~~~ **checkbox选中** ~~~ <input type="checkbox" th:checked="${q.remark eq 'checked'}" name="remark1" id="z1" th:value="${}"> ~~~ **字符串拼接** ~~~ <span th:text="'Welcome to our application, ' + ${userName} + '!'"></span> ~~~ 字符串串拼接还有另外⼀一种简洁的写法: ~~~ <span th:text="|Welcome to our application, ${userName} !|"></span> ~~~ ## URL URL 在 Web 应⽤用模板中占据着⼗十分重要的地位,需要特别注意的是 Thymeleaf 对于 URL 的处理理是通过语 法 @{...} 来处理理的。如果需要 Thymeleaf 对 URL 进⾏行行渲染,那么务必使⽤用 th:href、th:src 等属性,下⾯面 是⼀一个例例⼦子: ~~~ <a th:href="@{http://www.ityouknow.com/{type}(type=${type})}">link1</a> <a th:href="@{http://www.ityouknow.com/{pageId}/can-use-springcloud.html(pageId=${ pageId})}">view</a> ~~~ 也可以使⽤用 `@{...}` 设置背景: ~~~ <div th:style="'background:url(' + @{${img url}} + ');'"> ~~~ 几点说明: * 上例例中 URL 最后的 `(pageId=${pageId}) `表示将括号内的内容作为 URL 参数处理理,该语法避免使 ⽤用字符串串拼接,⼤大提⾼高了了可读性; * `@{...}` 表达式中可以通过{pageId}访问Context中的pageId变量 ## 三目运算符 在表单标签中显示内容使⽤用: `th:value="${age gt 30 ? '中年年':'年年轻'}" `表示如果 age ⼤大于 30 则显示中年年,否则显示年年轻。 * `gt:great than(⼤大于) ` * `ge:great equal(⼤大于等于)` * `eq:equal(等于)` * `lt:less than(⼩小于) ` * `le:less equal(⼩小于等于) ` * `ne:not equal(不不等于)` 结合三⽬目运算也可以将上⾯面的 if else 改成这样: ~~~ <a th:if="${flag eq 'yes'}" th:href="@{http://favorites.ren/}"> favorites </a> ~~~ ## switch/case ~~~ <div th:switch="${sex}"> <p th:case="'woman'">她是⼀一个姑娘...</p> <p th:case="'man'">这是⼀一个爷们!</p> <!-- *: case的默认的选项 --> <p th:case="*">未知性别的⼀一个家伙。</p> </div> ~~~ ## 传递list 我们都知道如果传入的是一个list集合,前端就必须要展示list集合的属性。 ~~~ public String index(Model model){ List<Student> list = ssi.findStudentByAge(15); model.addAttribute("s",list) return "index"; } ~~~ ~~~ <table th:each="i:${s}"> <tr > <td>学生Id</td> <td th:text="${i.id}"></td> </tr> <tr > <td>学生姓名</td> <td th:text="${i.name}"></td> </tr> <tr > <td>学生分数</td> <td th:text="${i.score}"></td> </tr> <tr > <td>教师建议</td> <td th:text="${i.suggestion}"></td> </tr> </table> ~~~ ## 传递对象 ~~~ public String index(Model model){ Student students = ssi.findStudentById(201713140001); model.addAttribute("s",students); return "index"; } ~~~ ~~~ <table th:each="i:${s}"> <tr > <td>学生Id</td> <td th:text="${i.getId(}"></td> </tr> <tr > <td>学生姓名</td> <td th:text="${i.getName()}"></td> </tr> <tr > <td>学生分数</td> <td th:text="${i.getScore()}"></td> </tr> <tr > <td>教师建议</td> <td th:text="${i.getSuggestion}"></td> </tr> </table> ~~~ # 在IDEA报红色 在IDEA中写Thymeleaf的语法,经常会遇到IDEA提示Thymeleaf语法错误,我推荐三个方法解决。 ## 第一个方法:idea设置 一劳永逸的,在File->Settings->Editor->inspections右边找到Thymeleaf下的Expression variables validation(当然也可以搜索) ![](https://img.kancloud.cn/8c/ae/8caea3be714aff4d9575d5e89fadcf6a_679x534.png) ## 第二个方法:suppress ~~~ 在 <!DOCTYPE html> 下加上 <!--suppress ALL--> ~~~ ~~~ <!DOCTYPE html> <!--suppress ALL--> ~~~ ## 第三个方法:写注释 ~~~ <!--/*@thymesVar id="say" type="com.jdxia.consumer.web"*/--> <p th:text="${say}"></p> ~~~