Spring Boot入门3——整合HTML
Spring Boot可以结合Thymeleaf模板来整合HTML,使用原生的HTML作为视图。
Thymeleaf模板时面向Web和独立环境的Java模板引擎,能够处理HTML、XML、JavaScript、CSS等。
如何使用
- 下载Thymeleaf插件
- 在入门1的项目的基础上进行修改
- 在配置文件pom.xml里添加Thymeleaf依赖
<!-- 继承父包 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.7.RELEASE</version>
</parent>
<dependencies>
<!-- web启动jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 使用lombok插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!-- 使用thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
- 在application.xml中配置视图解析器
server:
port: 9090
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML5
encoding: UTF-8
- 在resources目录下创建一个templates目录,创建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
- 测试,运行项目后在浏览器输入
localhost:8080/index/index
- 修改IndexHandler和index.html,控制器奖处理完的数据存放在一个Model对象中,前端html通过thymeleaf标签获取从后端传过来的数据
import com.southwind.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/index")
public class IndexHandler {
@GetMapping("/index")
public String index(Model model){
System.out.println("index...");
List<Student> list = new ArrayList<>();
list.add(new Student(1L, "张三", 23));
list.add(new Student(2L, "李四", 24));
list.add(new Student(3L, "王五", 25));
model.addAttribute("list",list);
return "index";
}
}
<!DOCTYPE html>
<htm xmlns:th="http://www.thymeleaf.org" ></htm>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello World</h1>
<table>
<tr>
<th>学生ID</th>
<th>学生姓名</th>
<th>学生年龄</th>
</tr>
<tr th:each="student:${list}">
<td th:text="${student.id}"></td>
<td th:text="${student.name}"></td>
<td th:text="${student.age}"></td>
</tr>
</table>
</body>
</html>
- 测试,运行项目后在浏览器输入
localhost:8080/index/index
目录结构
总结
可以通过Thymeleaf模板来整合HTML,HTML效率会比JSP高。
注意
- 放在
resources
里的templates
目录下的HTML文件是不能够直接访问
在浏览器路径输入http://localhost:8080/templates/index.html
,不能够直接访问
在浏览器路径输入http://localhost:8080/templates/jspTest.jsp
,也不能够直接访问
- 放在
resources
里的static
目录下的HTML文件是能够直接访问
在浏览器路径输入http://localhost:8080/staticTest.html
所以如果希望客户端能直接访问HTML资源,将这些资源放在static路径下即可。
否则必须通过控制器Controller的后台映射才能访问静态资源。