在IDEA中创建springBoot项目之后,测试templates中的html文件,发现启动项目之后写了controller控制器去打开相应的html文件,但是发现页面一直显示不出来。
controller如下:
mport org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author mazhicheng
* @date 2020/5/1 - 12:07
*/
@Controller
public class IndexController {
@GetMapping("/index")
public String index() {
return "index";
}
}
最后发现问题的起因在thymeleaf的使用中。
由于html是静态文件,所以放在templates中是不能被解析的,所以要使用thymeleaf。因此要在pom.xml中引入thymeleaf。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
注意:!!!
在pom.xml中引入了thymeleaf之后,可能由于某些原因,maven中没有加载进thymeleaf,因此做好重现加载maven文件,确保thymeleaf的导入(上次我的问题就是这里,写了配置之后没有手动加载maven)
如果此时还是不能显示templates中的html页面,还有可能是thymeleaf没有指定相应的版本所导致。需要在pom.xml中指定thymeleaf的版本。(由于版本更新的原因,在指定版本之后还是有可能报错,这个时候要多在网上搜一下,选择可用的版本更新的配置写进去,就是下面这个)
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>