springboot系列之模板引擎thymeleaf
页面模板引擎有JSP、Velocity、Freemarker、Thymeleaf等等,在springboot中,推荐使用Thymeleaf模板引擎,因为thymeleaf语法更简单,功能更强大。
一、引入thymeleaf
在pom.xml文件中引入thymeleaf依赖,如下:
1.8
UTF-8
UTF-8
3.0.11.RELEASE
2.1.1
org.springframework.boot
spring-boot-starter-thymeleaf
二、thymeleaf的基本使用
在使用thymeleaf时,我们只要把html页面放在classpath:/resources/templates下面,thymeleaf就能自动渲染;如果启动项目时,页面无法访问报404,有可能是thymeleaf版本和springboot版本不一致导致,springboot版本和thymeleaf版本有很大的关系会影响到页面,导致报404无法找到页面。
1、在html页面中导入thymeleaf的命名空间:
controller:
@Controller
@RequestMapping("/first")
public class HelloWorldController {
private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);
@RequestMapping("/test1")
public String sayHello(Model model) {
model.addAttribute("hello","hello thymeleaf!!!");
return "test";
}
}
thymeleaf页面如下:
测试thymeleaf的基本使用
从
启动项目,进行访问,效果如下:
2、thymeleaf基本语法
基础语法参见thymeleaf官方文档:https://www.thymeleaf.org/documentation.html