您的位置:首页 > 编程语言 > Java开发

分享知识-快乐自己:springboot之thymeleaf (1):简单的thymeleaf例子

2018-09-10 21:20 696 查看

之前搞springboot时,发现spring很推荐thymeleaf,所以看了看学了学,感觉不错,做个笔记先。

做个简单和例子,项目是springboot,所以引入themeleaf相关包

pom.xml

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

接着写个controller

@RequestMapping("/")
public String hello(Model model, HttpServletRequest request) {
// 文本表达式
model.addAttribute("name", "ywj");
// 获取对象属性
model.addAttribute("user", new User("ywj3"));
// 获取session文本
request.getSession().setAttribute("sname", "name from session");
// 获取session对象属性
request.getSession().setAttribute("suser", new User("name from session"));
// 显示html效果
model.addAttribute("html", "<b>BBB</b>");
// 数组
String[] arr = {"a", "b"};
model.addAttribute("arr", arr);
// url
model.addAttribute("url", "http://www.baidu.com");
model.addAttribute("today", new Date());
return "index";
}

 

接着在src/main/resources/templates中创建一个index.html,是html,不是jsp 然后看看thymeleaf语法:

///
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Hello Thymeleaf!</title>
</head>
<body>
文本表达式:
<span th:text="${name}" /><hr/>
文本表达式,获取对象属性:
<span th:text="${user.name}" /><hr/>
session中文本:
<span th:text="${session.sname}" /><hr/>
session中对象属性:
<span th:text="${session.suser.name}" /><hr/>
html效果:
<span th:utext="${html}" /><hr/>
url:
<a th:href="@{${url}}">baidu</a><hr/>
url跳转
<a th:href="@{/b}">效果是:127.0.0.1/项目名/b</a><hr/>
url还参数,效果:/c?a=aaa&b=bbb.还有一种@{/c/{a}(a='aaa'))} = /c/aaa
<a th:href="@{/c(a='aaa',b='bbb')}">url带参数</a><hr/>
url同一服务器下请求别的项目,比如项目A和项目thymeleaf1是同一个服务器里页的,项目A请求项目thymeleaf1里的方法,就用~/thymeleaf1/方法
<a th:href="@{~/thymeleaf1/c(a='aaa',b='bbb')}">url带参数</a><hr/>
数字可加减乘除余
<span th:text="1" />加:1+2=<span th:text="${1+2}" />减:2-1=<span th:text="${2-1}" />
乘:2*3=<span th:text="${2*3}" />除:6/2=<span th:text="${6/2}" />余:3%2=<span th:text="${3%2}" /><hr/>
数字比较:<!-- gt(>),lt(<),ge(>=),le(<=),not(!) eq(==),neq/ ne(!=) -->
<span th:if="${2 > 1}">2大于1</span>
<span th:if="2 < 1">2大于1</span>
时间格式:
<span th:text="${#dates.format(today, 'yyyy-MM-dd HH:mm:ss')}">13 May 2011</span>
</body>
</html>///

 

 

 

 

 

(注:更多详解请跳转:https://blog.csdn.net/u013845177/article/category/7226505)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: