Springboot+Thymeleaf 第一个demo

Thymeleaf简介

Thymeleaf和Freemarker,Velocity一样,是Springboot大力支持的三种模板语言之一。它可以完全替代JSP,事实上,在使用内嵌tomcat时,springboot对JSP不能很好的支持。

相交另外两种模板语言,Thymeleaf主要有以下三个优点:

1、Thymeleaf在有网络和无网络的环境下都可以运行。即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

2、Thymeleaf具有开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

3、Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

项目结构

首先引入pom文件

因为spring-boot-starter-thymeleaf中包含了spring-boot-starter-web所以不需要引入后者。

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.damai</groupId>
	<artifactId>springboot-thymleaf-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.1.RELEASE</version>
	</parent>

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

配置文件

classpath默认是/src/main/resources

server.port=8080

spring.thymleaf.prefix=classpath:/templates/
spring.thymleaf.suffix=.html

启动类

@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);

	}

}

控制类

@Controller
public class IndexController {

	@RequestMapping(value="index",method=RequestMethod.GET)
	public String index(Model model){
		model.addAttribute("name","xl");
		return "/index";
	}
}

运行

猜你喜欢

转载自blog.csdn.net/u014209205/article/details/81317096