《Java从入门到放弃》框架入门篇:在SpringBoot中使用thymeleaf模板

使用thymeleaf的好处:

1. 前后端分离:通过<span th:text="${user.name}">姓名</span>的语法方式,让美工在浏览器看到的是“姓名”,而程序员在服务器运行后显示user.name对应的数据。

2. 兼容多种方言,可直接套用模板实现JSTL、OGNL,快速实现表单绑定、属性编辑、国际化等功能。

常用th相关关键字如下表:

关键字

功能介绍

th:id

替换id

th:text

文本替换

th:utext

支持html的文本替换

th:object

替换对象

th:value

属性赋值

th:with

变量赋值运算

th:style

设置样式

th:onclick

点击事件

th:each

属性赋值

th:if

判断条件

th:unless

和th:if判断相反

th:href

链接地址

th:switch

多路选择 配合th:case 使用

th:case

th:switch的一个分支

th:fragment

布局标签,定义一个代码片段,方便其它地方引用

th:include

布局标签,替换内容到引入的文件

th:replace

布局标签,替换整个标签到引入的文件

th:selected

selected选择框 选中

th:src

图片类地址引入

th:inline

定义js脚本可以使用变量

th:action

表单提交的地址

th:remove

删除某个属性

th:attr

设置标签属性,多个属性可以用逗号分隔

OK,关于thymeleaf就先介绍这么些,后期需要使用时,再详细介绍对应内容。

 

接下来开始在springboot中使用thymeleaf显示数据,步骤如下:

第一步、在pom.xml中添加如下配置

    <!-- 引入thymeleaf模板引擎依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

第二步、在application.yml中的添加如下配置,如果spring已经存在,则合并。

spring:   
    thymeleaf:
        prefix: classpath:/templates/
        suffix: .html
        mode: HTML5
        encoding: utf-8
        servlet:
            content-type: text/html
        cache: false

第三步、在src/main/resources下添加templates目录,在目录中添加index1.html文件,文件代码如下:

<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        姓名:<span th:text="${session.author.username}">哈哈</span>
    </body>
</html>

第四步、修改Controller文件,内容如下:

@Controller
public class AuthorController {
	@Autowired
	private AuthorService authorService;
	
	@RequestMapping("/hello")
	public String hello(HttpSession session){
		Author author = authorService.findById(1);
		System.out.println(author.getUsername());
		session.setAttribute("author", author);
		return "index1";
	}
}

注意:将@RestController更改为@Controller,因为@RestController是把return返回的内容直接显示在浏览器,而@Controller表示当前类只是一个控制器,return表示跳转到指定页面。

第五步、运行App,并访问localhost:8080/hello,成功显示结果

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值