先看下我的工程结构
首先需要加入thymeleaf的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
然后在application配置文件内配置一些参数
.yaml文件
thymeleaf:
#关闭thymeleaf缓存
cache: false
#在构建URL时预先查看名称的前缀,默认:resources/templates/
prefix: /WEB-INF/views/
#构建URL时附加查看名称的后缀
suffix: .html
.properties文件
#关闭thymeleaf缓存
spring.thymeleaf.cache=false
#在构建URL时预先查看名称的前缀,默认:resources/templates/
spring.thymeleaf.prefix = /WEB-INF/views/
#构建URL时附加查看名称的后缀
spring.thymeleaf.suffix = .html
配置好了配置文件后就可以访问html啦
值得注意的是如果你报下面这个错误的话。
那就要好好检查下.yaml文件是否配置正确了,yaml是十分讲究缩进的,如果第二个节点跟上一个节点的子节点在一个位置那就没用了比如
不过静态文件会报404
需要创建一个静态资源配置的类
package org.wcy.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* <p>Title : MyWebMvcConfig</p>
* <p>Description : 自定义静态资源映射路径和静态资源存放路径</p>
* <p>DevelopTools : Eclipse_x64_v4.7.1</p>
* <p>DevelopSystem : Windows 10</p>
* <p>Company : org.wcy</p>
* @author : WangChenYang
* @date : 2018年11月14日 下午9:07:33
* @version : 0.0.1
*/
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
/**
* 在Spring添加拦截器之前先创建拦截器对象,这样就能在Spring映射这个拦截器前,把拦截器中的依赖注入的对象给初始化完成了。
* </br>避免拦截器中注入的对象为null问题。
* @return
*/
/*@Bean
public SecurityInterceptor getSecurityInterceptor(){
return new SecurityInterceptor();
}*/
/**
* 添加自定义静态资源映射路径和静态资源存放路径(图片)
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("配置静态资源");
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/WEB-INF/resources/");
super.addResourceHandlers(registry);
}
/**
* 添加拦截器
* @param registry
*/
/*@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(getSecurityInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}*/
}
如果你在开发过程中报下面这个错误的话就要加入这个依赖然后在配置文件内配置spring.thymeleaf.mode=LEGACYHTML5
springboot2.0以上则无需担心这个问题由于Thymeleaf是HTML5的所以比较严格但是springboot2.0后解决了这个问题
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>