一:模板引擎的介绍:
FreeMarker
Thymeleaf
Velocity (1.4版本之后弃用,Spring Framework 4.3版本之后弃用)
Groovy
Mustache
注:jsp应该尽量避免使用,原因如下:
- jsp只能打包为:war格式,不支持jar格式,只能在标准的容器里面跑(tomcat,jetty都可以)
- 内嵌的Jetty目前不支持JSPs
- Undertow不支持jsps
- jsp自定义错误页面不能覆盖spring boot 默认的错误页面
Thymeleaf 是一个优秀的、面向Java 的XML庆HTML/HTML5 页面模板,具有丰
富的标签语言和函数。因此,在使用Spring Boot 框架进行页面设计时, 一般都会选择Thymeleaf 模板。
一:Thymeleaf模板引擎使用:
1;引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2:配置文件:
server.port=8081
###ThymeLeaf配置
#模板的模式,支持 HTML, XML TEXT JAVASCRIPT
spring.thymeleaf.mode=HTML5
#编码 可不用配置
spring.thymeleaf.encoding= UTF-8
#开发配置为false,避免修改模板还要重启服务器
spring.thymeleaf.cache= false
#配置模板路径,默认是templates,可以不用配置
spring.thymeleaf.prefix=classpath:/templates
3;编写代码Controller
@RequestMapping("/thymeleaf")
public ModelAndView thymeleaf(){
User user = new User();
user.setName("wsj");
user.setAge(100);
ModelAndView mv = new ModelAndView();
mv.addObject("user", user);
mv.setViewName("/user/user.html");
return mv;
}
User文件:
package com.wsj.springbootdemo.bean;
/**
* 项目名称:User;
* 类 名 称:User;
* 类 描 述:TODO ;
* 创 建 人:Angus;
* 创建时间:2020/2/15 20:17;
*
* @version:1.0
**/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4:编写魔板页:在templates下的user文件夹建user.html测试页面,内容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Show User</title>
</head>
<body>
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
</tr>
<tr>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>
</body>
</html>
运行代码查看结果:
至此;templates模板在SpringBoot中使用结束
至于templates的语法和使用可以参考官网文档https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
本文代码github地址:https://github.com/itwsj/springbootdemo