springboot开发->springboot+thymeleaf

856 阅读3分钟

thymeleaf介绍:

Thymeleaf是个XML/XHTML/HTML5模板引擎,可以用于Web与非Web应用。 

thymeleaf优点:静态html嵌入标签属性,浏览器可以直接打开模板文件,便于前后端联调。springboot官方推荐方案。 

thymeleaf缺点:模板必须符合xml规范,就这一点就可以判死刑!太不方便了!js脚本必须加


thymeleaf创建步骤:

1.首先新建一个springboot项目

2.pom.xml的设置

<?xmlj 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.knet.domain</groupId>
    <artifactId>knet-record-information-task</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>knet-record-information-task</name>
    <description>springboot项目</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
       <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>

3.application.yml文件的设置

spring:
  thymeleaf:
    cache: false #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
  mvc:
    date-format: yyyy-MM-dd
server:
  port: 80

如果不适用默认的thymeleaf的路径,可以进行自行设置(原因见6.原理部分)

spring:  
 thymeleaf:
    prefix: classpath:/templates/  #prefix:指定模板所在的目录
    check-template-location: true  #check-tempate-location: 检查模板路径是否存在
    cache: false  #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
    suffix:  .html
    mode: HTML5
    encoding: utf-8

4.页面的编写

​
@Controller
public class IndexController {
     @RequestMapping(value = {"index","/"})
    public String index(){
        return "index";
    }
    @RequestMapping(value = {"/login"})
    public ModelAndView login(){
        Map map=new HashMap<>();
        map.put("welcome","welcome you!");
        return new ModelAndView("login",map);
    }
}

templates文件间下创建页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>用户管理系统</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body class="container">
<div id="wrapper" class="toggled">
   index
    </div>
</body>
</html>

login页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>用户管理系统</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body class="container">
<div id="wrapper" class="toggled">
   登录<h3 th:text="${welcome}" style="color: red"></h3>
    </div>
</body>
</html>

5.thymeleaf的使用

具体的使用可查看官方文档:www.thymeleaf.org/

后续会介绍thymeleaf的使用

6.实现原理:

1) 
@EnableAutoConfiguration
public @interface SpringBootApplication 
    2)
    @Import({AutoConfigurationImportSelector.class})
    public @interface EnableAutoConfiguration 
        protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,          AnnotationAttributes attributes) {
        List<String> configurations =                                   SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

在META-INF/spring.factories文件中配置很多要自动装配的类,其中就包括:

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider

查看ThymeleafTemplateAvailabilityProvider这个类可看到,默认的前后缀及加载地址的设置:

public class ThymeleafTemplateAvailabilityProvider implements TemplateAvailabilityProvider {
    public ThymeleafTemplateAvailabilityProvider() {
    }
​
    public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader, ResourceLoader resourceLoader) {
        if (ClassUtils.isPresent("org.thymeleaf.spring5.SpringTemplateEngine", classLoader)) {
            String prefix = environment.getProperty("spring.thymeleaf.prefix", "classpath:/templates/");
            String suffix = environment.getProperty("spring.thymeleaf.suffix", ".html");
            return resourceLoader.getResource(prefix + view + suffix).exists();
        } else {
            return false;
        }
    }
}

所以可以使用来改变thymeleaf模板的路径等

spring:  
 thymeleaf:
    prefix: classpath:/templates/  #prefix:指定模板所在的目录
    check-template-location: true  #check-tempate-location: 检查模板路径是否存在
    cache: false  #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
    suffix:  .html
    mode: HTML5
    encoding: utf-8