5分钟创建一个SpringBoot + Themeleaf的HelloWord应用
第一步:用IDE创建一个普通maven工程,我用的eclipse.
第二步:修改pom.xml,加入支持SpringBoot和Themeleaf的依赖,文件内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 <modelVersion>4.0.0</modelVersion> 5 6 <groupId>com.chry</groupId> 7 <artifactId>spring-boot-thymeleaf</artifactId> 8 <version>0.0.1</version> 9 <packaging>jar</packaging> 10 11 <properties> 12 <java.version>1.7</java.version> 13 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 14 </properties> 15 16 <name>spring-boot-thymeleaf</name> 17 <description>Spring Boot with Thymeleaf</description> 18 19 <!-- Inherit defaults from Spring Boot --> 20 <parent> 21 <groupId>org.springframework.boot</groupId> 22 <artifactId>spring-boot-starter-parent</artifactId> 23 <version>1.4.0.RELEASE</version> 24 </parent> 25 26 <dependencies> 27 <dependency> 28 <groupId>org.springframework.boot</groupId> 29 <artifactId>spring-boot-starter-thymeleaf</artifactId> 30 </dependency> 31 32 <dependency> 33 <groupId>org.springframework.boot</groupId> 34 <artifactId>spring-boot-starter-test</artifactId> 35 <scope>test</scope> 36 </dependency> 37 </dependencies> 38 39 <build> 40 <plugins> 41 <plugin> 42 <groupId>org.springframework.boot</groupId> 43 <artifactId>spring-boot-maven-plugin</artifactId> 44 </plugin> 45 </plugins> 46 </build> 47 48 </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 看效果。