第一步:用IDE创建一个普通maven工程,我用的eclipse.
第二步:修改pom.xml,加入支持SpringBoot和Themeleaf的依赖,文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<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.chry</groupId>
<artifactId>spring-boot-thymeleaf</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging> <properties>
<java.version>1.7</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <name>spring-boot-thymeleaf</name>
<description>Spring Boot with Thymeleaf</description> <!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
第三步:创建SpringBoot应用主类
package com.chry.springboot; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class SpringBootThymeleafApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootThymeleafApp.class, args);
}
}
第四步: 创建HelloWorldController类, 返回值"index“将用于对映后面要创建的index.html
package com.chry.springboot.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class HelloWorldController {
@RequestMapping("/")
public String index() {
return "index";
}
}
第五步:在src/main/resources/templates下创建要显示Hello World的index.html文件,加入Themeleaf头,文件必须是XHTML格式,否则运行会报异常。
由于XHTML格式检查很严格,文件大了不好查找。可以找一些在线格式化网站帮助检查,用XML格式检查就可以
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Boot and Thymeleaf example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h3>Spring Boot and Thymeleaf</h3>
<p>Hello World!</p>
</body>
</html>
第六步:用maven build工程, 生成spring-boot-thymeleaf-0.0.1.jar
第七步: 运行java -jar spring-boot-thymeleaf-0.0.1.jar, 然后浏览器http://localhost:8080 看效果。