thymeleaf取model值_史上最详 Thymeleaf 使用教程

点击上方“桌前明月”,可以关注我偶。

fd9745a102929480284bbef4b48621e7.png

前言

操作前建议先参考我的另一篇博客:玩转 SpringBoot 2 快速整合 | Thymeleaf 篇 查看如何在SpringBoot 中使用 Thymeleaf。还有一点需要注意的是:模版页面中的 html 上需要声明 Thymeleaf 的命名空间,具体代码如下:

<html xmlns:th="http://www.thymeleaf.org">

接下来就可以开始 Thymeleaf 使用教程了!

全文介绍 Thymeleaf 是基于 Thymeleaf 3.0.11.RELEASE 版本进行说明的。

基础语法

文本标签 th:text/th:utext

用于文本内容的显示操作。

  1. th:text 进行文本替换 不会解析html

  2. th:utext 进行文本替换 会解析html

代码演示:

    @RequestMapping("/th")
public String th(Model model){
String msg = "

我是h1

";
model.addAttribute("msg",msg);
return "/course/th";
}

th:text 进行文本替换 不会解析html

<p th:text="text标签:  + ${msg}">p>

结果页面:

<p>text标签:<h1>我是h1h1>p>

游览器访问的效果:5a3bc0c499651c9317955c4905944fa2.png

th:utext 进行文本替换 会解析html

<p th:utext="utext标签: + ${msg}">p>

游览器展示效果如下图:26bfac6016d8e0abadca55290159b62a.png
使用 + 和 | | 效果是一样的,如下代码所示:

<p th:utext="utext标签: + ${msg}">p>
<p th:utext="|utext标签: ${msg}|">p>

字符串拼接

拼接字符串通过 + 或者 | 进行拼接

代码演示:

    @RequestMapping("/th")
public String th(Model model){
model.addAttribute("a",1);
model.addAttribute("b",2);
return "/course/th";
}

模版页面:

<p th:text="${a}+${b}">p>

结果页面:

<p>3p>

模版页面:

<p th:text="|${a} ${b}|">p>

结果页面:

<p>1 2p>

模版页面:

<p th:text="${a} > ${b}">p>

结果是:

<p>falsep>

java代码:

    @RequestMapping("/th")
public String th(Model model){
model.addAttribute("flag",true);
return "/course/th";
}

模版页面:

<p th:text="!${flag}">p>

结果页面:

<p>falsep>

*{...}和 ${...}表达式

正常情况下 {...} 和 ${...}是一样的,但是 {...} 一般和 th:object 进行一起使用来完成对象属性的简写。

代码演示:

    @RequestMapping("/th")
public String th(Model model){
User user = new User("ljk",18);
model.addAttribute("user",user);
return "/course/th";
}

使用 ${...}操作
模版代码:

<p th:text="${user.name}">p>
<p th:text="${user.age}">p>

结果页面:

<p>ljkp><p>18p>

使用 *{...}操作
模版代码:

<p th:text="*{user.name}">p>
<p th:text="*{user.age}">p>

结果页面:

<p>ljkp><p>18p>

使用 *{...}特有操作
模版代码:

<div th:object="${user}" >
<p th:text="*{name}">p>
<p th:text="*{age}">p>
div>

结果页面:

<p>ljkp><p>18p>

#{...}表达式

用于国际化message.properties 属性读取
定义message.properties 配置文件a8d7c45c46f0987bf912bf03e7803e37.png3b325f82fb540db2a1df58307beb3011.png

定义国际化处理转换处理类

@Configuration
public class LocaleResolverConfig {
@Bean(name="localeResolver")
public LocaleResolver localeResolverBean() {
return new SessionLocaleResolver();
}
}

定义国际化处理的controller


@Controller
public class ProductController {

@Autowired
private LocaleResolver localeResolver;
private ProductService productService = new ProductService();

@RequestMapping("/")
public String useT(Model model,HttpServletRequest request,HttpServletResponse response) {
//设置访问用户信息到session
request.getSession(true).setAttribute("user", new User("桌前", "明月", "CHINA", null));
localeResolver.setLocale(request,response,Locale.CHINA);
return "productList";
}
}

如果没有定义 message_en_US.properties 和 message_zh_CN.properties 会默认取message.properties中的信息
如果 Locale = Locale.CHINA 就取 message_zh_CN.properties
如果 Locale = Locale.US 就取 message_en_US.properties。

模版代码:

<p th:utext="#{home.welcome(${session.user.name})}">Welcome to our grocery store, Sebastian!p>

访问controller的路径的效果:4dd1c4cb1c17ac03906f4a0e6a144be7.png

~{...}片段表达式

这个一般和模版布局的语法一起使用,具体使用方式请看下面模版布局的教程。

@{...}链接网址表达式

一般和 th:href、th:src进行结合使用,用于显示Web 应用中的URL链接。通过@{...}表达式Thymeleaf 可以帮助我们拼接上web应用访问的全路径,同时我们可以通过()进行参数的拼接

代码演示:

模版代码:

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

结果页面:

<img src="/sbe/images/gtvglogo.png">

模版代码:

<a th:href="@{/product/comments(prodId=${prod.id})}" >查看a>

结果页面:

<a href="/sbe/product/comments?prodId=2">查看a>

模版代码:

 <a  th:href="@{/product/comments(prodId=${prod.id},prodId2=${prod.id})}" >查看a>

结果页面:

<a href="/sbe/product/comments?prodId=2&prodId2=2">查看a>

条件判断 th:if/th:unless

th:if 当条件为true则显示。th:unless 当条件为false 则显示。

代码演示:

java代码:

    @RequestMapping("/thif")
public String thif(Model model){
model.addAttribute("flag",true);
return "/course/thif";
}

模版页面:

<p th:if="${flag}">if判断p>

结果页面:

<p>if判断p>

模版页面:

<p th:unless="!${flag}">unless 判断p>

结果页面:

<p>unless 判断p>

switch

th:switch 我们可以通过switch来完成类似的条件表达式的操作。代码演示:
java代码:

    @RequestMapping("/thswitch")
public String thswitch(Model model){
User user = new User("ljk",23);
model.addAttribute("user",user);
return "/course/thswitch";
}

模版页面:

<div th:switch="${user.name}">
<p th:case="'ljk'">User is ljkp>
<p th:case="ljk1">User is ljk1p>
div>

结果页面:

<div><p> User is ljkp>div>

for循环

th:each 遍历集合

代码演示:
java代码:

    @RequestMapping("/theach")
public String theach(Model model){

List userList = new ArrayList();
User user1 = new User("ljk",18);
User user2 = new User("ljk2",19);
User user3 = new User("ljk3",20);
User user4 = new User("lj4",21);
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
model.addAttribute("userList",userList);
List strList = new ArrayList();
strList.add("ljk");
strList.add("ljk2");
strList.add("ljk3");
strList.add("lj4");
model.addAttribute("strList",strList);return "/course/theach";
}

模版页面:

     <table>
<thead>
<tr>
<th>用户名称th>
<th>用户年龄th>
tr>
thead>
<tbody>
<tr th:each="user : ${userList}" th:class="${userStat.odd}? 'odd'">
<td th:text="${user.name}">Onionstd>
<td th:text="${user.age}">2.41td>
tr>
tbody>
table>
----------------------------------------------------------------------
<table>
<thead>
<tr>
<th>用户名称th>
tr>
thead>
<tbody>
<tr th:each="str : ${strList}" th:class="${strStat.odd}? 'odd'">
<td th:text="${str}">Onionstd>
tr>
tbody>
table>

结果页面:7bdebb1d13f9d5e1fe392093a9d602dc.png

我们可以通过便利的变量名+Stat 来获取索引 是否是第一个或最后一个等。
便利的变量名+Stat称作状态变量,其属性有:

  • index:当前迭代对象的迭代索引,从0开始,这是索引属性;

  • count:当前迭代对象的迭代索引,从1开始,这个是统计属性;

  • size:迭代变量元素的总量,这是被迭代对象的大小属性;

  • current:当前迭代变量;

  • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算);

  • first:布尔值,当前循环是否是第一个;

  • last:布尔值,当前循环是否是最后一个

for循环介绍内容参考了 CSDN博主 【liubin5620 Thymeleaf模板引擎常用属性之 th:each迭代循环】:https://blog.csdn.net/liubin5620/article/details/80470619

th:href

用于声明在a 标签上的href属性的链接 该语法会和@{..} 表达式一起使用。

代码演示:
java代码:

    @RequestMapping("/thhref")
public String thhref(Model model){
return "/course/thhref";
}

模版代码:

<a href="../home.html" th:href="@{/}">返回首页a>

结果页面:

<a href="/sbe/">返回首页a>

th:class

用于声明在标签上class 属性信息。

代码演示:
java代码:

    @RequestMapping("/thclass")
public String thclass(Model model){
return "/course/thclass";
}

模版页面:

<p th:class=" 'even'? 'even' : 'odd'" th:text=" 'even'? 'even' : 'odd'">p>

结果页面:

<p class="even">evenp>

th:attr

用于声明html中或自定义属性信息。

代码演示:

java代码:

@RequestMapping("/thattr")
public String thattr(Model model){
return "/course/thattr";
}

模版页面:

<img  th:attr="src=@{/images/gtvglogo.png}" />

结果页面:

<img src="/sbe/images/gtvglogo.png">

th:value

用于声明html中value属性信息。

代码演示:
java代码:

@RequestMapping("/thvalue")
public String thvalue(Model model){
model.addAttribute("name", "ljk");
return "/course/thvalue";
}

模版页面:

    <input type="text" th:value="${name}" />

结果页面:

<input type="text" value="ljk">

th:action

用于声明html from标签中action属性信息。

代码演示:
java代码:

@RequestMapping("/thaction")
public String thaction(Model model){
return "/course/thaction";
}

模版页面:

    <form action="subscribe.html" th:action="@{/subscribe}">
<input type="text" name="name" value="abc"/>
form>

结果页面:

<form action="/sbe/subscribe">
<input type="text" name="name" value="abc">
form>

th:id

用于声明htm id属性信息。

代码演示:
java代码:

    @RequestMapping("/thid")
public String thid(Model model){
model.addAttribute("id", 123);
return "/course/thid";
}

模版页面:

<p th:id="${id}">p>

结果页面:

<p id="123">p>

th:inline

JavaScript内联 操作使用的语法,具体请参考下面内联操作相关介绍

th:onclick

用于声明htm 中的onclick事件。

代码演示:
java代码:

@RequestMapping("/thonclick")
public String honclick(Model model){
return "/course/thonclick";
}

模版页面:

<html><head><meta charset="UTF-8"><title>Insert title heretitle><script type="text/javascript">function showUserInfo(){
    
alert("i am z
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你在使用 Thymeleaf 时遇到了页面报错,可以查看控制台输出的错误信息,找到具体的问题所在。常见的错误包括语法错误、模板引用错误、标签使用错误等等。 如果你想利用 Thymeleaf 自定义错误页面,可以按照以下步骤进行: 1. 首先在 `src/main/resources/templates` 目录下创建一个 `error` 目录。在该目录下创建一个名为 `error.html` 的 Thymeleaf 模板文件。 2. 在 `application.properties` 文件中配置错误处理的地址: ``` server.error.path=/error ``` 3. 创建一个名为 `ErrorController` 的控制器类,用于处理错误请求: ```java @Controller public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController { @RequestMapping("/error") public String handleError(HttpServletRequest request, HttpServletResponse response) { // 获取错误状态码 Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); // 根据状态码返回不同的错误页面 if (statusCode == 404) { return "error/404"; } else { return "error/500"; } } @Override public String getErrorPath() { return "/error"; } } ``` 4. 在 `error` 目录下创建 `404.html` 和 `500.html` 两个 Thymeleaf 模板文件,用于显示不同类型的错误页面。 例如,`404.html` 可以这样编写: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>404 Not Found</title> </head> <body> <h1>404 Not Found</h1> <p>您请求的页面不存在,请检查您输入的地址是否正确。</p> </body> </html> ``` 5. 访问不存在的页面,尝试触发 404 错误,可以看到自定义的错误页面。 如果你想测试 500 错误,可以在控制器中抛出一个异常,例如: ```java @RequestMapping("/test") public String test() { throw new RuntimeException("测试错误"); } ``` 然后访问 `/test` 地址即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值