用springboot和thymeleaf连接前后端
时间: 2023-12-03 20:46:01 浏览: 119
连接前后端一般有两种方式:
1. 前后端分离,使用RESTful API进行数据传输。
2. 后端渲染模板,将数据直接嵌入到HTML页面中返回给前端。
以下是使用Spring Boot和Thymeleaf进行后端渲染的步骤:
1. 配置pom.xml文件,添加Spring Boot和Thymeleaf的依赖。
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 创建Controller类,在该类中定义RequestMapping,处理前端请求,并返回视图名称。
```java
@Controller
public class MyController {
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("name", "World");
return "index";
}
}
```
3. 创建模板文件,在resources/templates目录下创建index.html文件。
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Thymeleaf</title>
</head>
<body>
<h1>Hello, <span th:text="${name}"></span>!</h1>
</body>
</html>
```
4. 配置application.properties文件,设置Thymeleaf视图解析器的前缀和后缀。
```
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
```
5. 运行Spring Boot应用程序,访问http://localhost:8080/,即可看到页面中展示了“Hello, World!”。
以上就是使用Spring Boot和Thymeleaf连接前后端的基本步骤。
阅读全文
相关推荐
















