thymeleaf渲染web页面
a.操作步骤:
1.导入prom依赖
2.在resource文件下创建application.yml配置文件
3.创建实体类User
4.创建控制器ThymeleafController
5.在resource文件下创建templates模板下的myThymeleaf.html页面
a.1.导入prom依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.guigu</groupId>
<artifactId>thmeleaf-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入模板依赖thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
a.2.在resource文件下创建application.yml配置文件
spring:
thymeleaf:
#prefix:指定模板所在的目录
prefix: classpath:/templates/
#检验模板路径是否存在
check-template-location: true
#是否缓存,开发者模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能
cache: true
suffix: .html
encoding: UTF-8
mode: HTML5
a.3.创建实体类User
package com.liujie.entity;
/**
* @ClassName UserEntity
* @Description TODO
* @Author liujie
* @Date 2021/6/18 20:48
* @Version 1.0
**/
public class UserEntity {
private String username;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public UserEntity(String username, Integer age) {
this.username = username;
this.age = age;
}
}
a.4.创建控制器ThymeleafController
package com.liujie.controller;
import com.liujie.entity.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @ClassName ThymeleafController
* @Description TODO
* @Author liujie
* @Date 2021/6/18 20:44
* @Version 1.0
**/
@Controller
public class ThymeleafController {
@RequestMapping("/myThymeleaf")
public String myThymeleaf(HttpServletRequest request){
request.setAttribute("user",new UserEntity("lingyi",20));
return "myThymeleaf";
}
}
a.5.在resource文件下创建templates模板下的myThymeleaf.html页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Show User</title>
</head>
<body>
<table>
姓名:<span th:text="${user.username}"></span>
年龄:<span th:text="${user.age}"></span>
</table>
</body>
</html>
b.出现的问题和解决方案
问题:
创建ThymeleafController控制器的时候,类上的注解给了@RestController,导致User对象效果出不来
解决方案:
将@RestController替换成@Controller,出现问题的原因是因为@RestController不经过视图解析器
c.效果展示
1.springboot启动类启动
2.页面访问效果