maven搭建springboot+thymeleaf
1.新建maven
自己创建包和文件夹。目录结构如下:


2.pom.xml
<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.ufo</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.启动类app.java:
package com.ufo.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class app {
public static void main(String[] args) {
SpringApplication.run(app.class, args);
}
}
4.testController.java
@Controller
public class testController{
@RequestMapping("/hello")
public String hello(HttpServletRequest request, @RequestParam(value = "name", defaultValue = "springboot-thymeleaf") String name) {
request.setAttribute("name", name);
return "hello";
}
}
5.配置文件application.yml:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
6.测试界面hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>springboot-thymeleaf测试</title>
</head>
<body>
<p th:text="'hello, ' + ${users} + '!'" />
</body>
</html>
启动启动类。成功。
7.thymeleaf列表
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>springboot-thymeleaf测试</title>
</head>
<body>
<table border="1">
<tr>
<th>用户名</th>
<th>邮箱</th>
<th>状态变量:index</th>
<th>状态变量:count</th>
<th>状态变量:size</th>
<th>状态变量:even</th>
<th>状态变量:odd</th>
</tr>
<tr th:each="user : ${users}" >
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<th th:text="${user.feature}"></th>
<th th:text="${user.status}"></th>
<th th:text="${user.dornum}"></th>
</tr>
</table>
</body>
</html>
8.thymeleaf的ifelse
<td th:switch = "${ user.status ==1 }" >
<div th:case="true" th:text = "在校" ></div>
<div th:case="false" th:text = "离校" ></div>
</td>
或者用三目运算:
th:text="${emp.gender==0?'女':'男'}"
9.小心只返回hello,不返回界面
用controller不用RestController
10.只编译html
spring.thymeleaf.cache=false
本文介绍了如何使用maven构建一个springboot项目,并集成thymeleaf模板引擎。从新建maven项目到配置pom.xml,再到编写启动类、控制器和配置文件,详细讲解了每个步骤。同时,提到了thymeleaf的列表展示和条件判断用法,以及在返回结果时避免只返回字符串而忽略视图渲染的问题。
2315

被折叠的 条评论
为什么被折叠?



