SpringBoot 集成thymeleaf

虾米哥 阅读:658 2021-03-31 18:15:28 评论:0

Thymeleaf 简介:

Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发,模板引擎是一个技术名词,是跨领域跨平台的概念,在Java语言体系下有模板引擎,在C#、PHP语言体系下也有模板引擎。除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。

Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。使用thymeleaf创建的html模板可以在浏览器里面直接打开(展示静态数据),这有利于前后端分离。需要注意的是thymeleaf不是spring旗下的。这里我们使用thymeleaf 3版本。

第一步:springboot 添加thymeleaf 依赖jar文件:

	<!--thymeleaf 模板依赖 --> 
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-thymeleaf</artifactId> 
		</dependency> 
        <!---去除thymeleaf关于HTML校验-> 
		<dependency> 
			<groupId>net.sourceforge.nekohtml</groupId> 
			<artifactId>nekohtml</artifactId> 
			<version>1.9.22</version> 
		</dependency>

第二步:application.properties 配置文件配置thymeleaf

# Thymeleaf setting
thymeleaf.cache=false   #是否启动缓存
thymeleaf.mode=LEGACYHTML5 #

 

第三步:在资源文件resource/templates,编写相关HTML(userInfo.html、userInfoAdd.html、userInfoDel.html)

userInfo.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>UserInfo</title> 
</head> 
<body> 
<h3>用户查询界面</h3> 
</body> 
</html>

userInfoAdd.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Add</title> 
</head> 
<body> 
<h3>用户添加界面</h3> 
</body> 
</html>

userInfoDel.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Del</title> 
</head> 
<body> 
<h3>用户删除界面</h3> 
</body> 
</html>

第四步:编辑后台逻辑代码和功能验证:

package com.zzg.controller; 
 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
 
@Controller 
@RequestMapping("/userInfo") 
public class UserInfoController { 
	/** 
     * 用户查询. 
     * @return 
     */ 
    @RequestMapping("/userList") 
    public String userInfo(){ 
        return "userInfo"; 
    } 
 
    /** 
     * 用户添加; 
     * @return 
     */ 
    @RequestMapping("/userAdd") 
    public String userInfoAdd(){ 
        return "userInfoAdd"; 
    } 
 
    /** 
     * 用户删除; 
     * @return 
     */ 
    @RequestMapping("/userDel") 
    public String userDel(){ 
        return "userInfoDel"; 
    } 
} 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号