视图解析:SpringBoot默认不支持JSP,需要引入第三方模板引擎技术实现页面渲染
视图的处理方式有三种:1)转发,2)重定向,3)自定义视图
Thymeleaf
导入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<!-- 记得加版本号-->
</dependency>
在springboot中,它已经给自动配置好了thymeleaf,可以在ThymeleafAutoConfiguration中查看。
使用thymeleaf
- 添加controller层
package com.example.springbootcode1.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @author: Eric
* @description: thymeleaf
* @date: 2022/5/26 23:45
* @version: 1.0
*/
@Controller
public class ViewTestController {
@GetMapping("/thymeleaf")
public String testThymeleaf(Model model) {
//model中的数据会放在请求域中 request.setAttribute("a", aa)
model.addAttribute("msg", "你好");
model.addAttribute("link", "www.baidu.com");
return "success";
}
}
- 添加html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${msg}">haha</h1>
<h2>
<a href="www.baidu.com" th:href="${link}">百度</a>
</h2>
</body>
</html>
使用${}来取值,里面放controller层中的Model参数
th:表示后面的值需要替换
- 启动 启动之后的样子如下:
也可以用下面的配置,实际开发中有时会经常遇到。
# 添加前置访问路径
server:
servlet:
context-path: /world
关于视图thymeleaf 和 前端框架vue,挖个坑,后面再详细介绍。