SpringBoot + Thymeleaf 整合实例讲解
一、项目结构
这个实例项目简单实现了SpringBoot + Thymeleaf的整合,通过访问URL,打开页面。
二、代码讲解
2.1 pom.xml
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- thymeleaf 需要导入该配置,这样才能使用thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>
2.2 启动类Application
@SpringBootApplication @Controller @ComponentScan(basePackages={ "com.test.spring.boot.controller"}) //自定义自动扫描 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@ComponentScan:自定义配置了要扫描的包,若有多个包,则用逗号分隔。
2.3 application.properties
# 服务端口 server.port=8082 # 日志配置 logging.config=classpath:logback.xml # thymeleaf配置 # 注释的部分是Thymeleaf默认的配置,如有其它需求可以自行更改 # spring.thymeleaf.prefix=classpath:/template/ # spring.thymeleaf.suffix=html # spring.thymeleaf.mode=HTML5 # spring.thymeleaf.encoding=UTF-8 # spring.thymeleaf.content-type=text/html spring.thymeleaf.cache=false
需要注意的是,thymeleaf默认的模板存放目录是templates,默认的后缀是html;因此,若大家在写项目的时候就是按照这种结构写的,那就不需要再进行配置了。
2.4 HelloController
@Controller @RequestMapping("/") public class HelloController { @RequestMapping("/hello") public String hello(Model model) { UserBean userBean = new UserBean(); userBean.setUsername("test_1"); model.addAttribute("user", userBean); return "hello"; } }
这个类是请求的Controller,注解和SpringMVC的注解一样,将用户信息组合添加到Model中,返回到hello.html页面。
2.5 main.css
.navbar-label { color: #008000; font-size: 50px; }
2.6 hello.html
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Springboot thymeleaf test</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" th:href="@{/css/main.css}"/> </head> <body> <div> <div> <label class="navbar-label" th:text="${user.username}">Hello World</label> </div> </div> </body> </html>
这里需要注意的是,需要替换添加 <html xmlns:th="http://www.thymeleaf.org"> 到页面的顶部。
最后,启动服务,访问即可跳转到hello.html页面。
对于thymeleaf不熟悉的小伙伴可以阅读下面这篇文章来学习下thymeleaf的基本语法吧~