springboot实现html页面交互
时间: 2023-05-29 22:03:40 浏览: 322
Spring Boot可以使用Thymeleaf模板引擎来实现HTML页面交互。以下是一个简单的示例:
1. 添加Thymeleaf依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 创建Thymeleaf模板
在src/main/resources/templates目录下创建一个HTML文件,例如index.html。在该文件中添加Thymeleaf模板标记,例如:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot Thymeleaf Demo</title>
</head>
<body>
<h1 th:text="${message}"></h1>
<form method="post" th:action="@{/submit}">
<input type="text" name="name" th:value="${name}" />
<button type="submit">Submit</button>
</form>
</body>
</html>
```
在上面的示例中,使用Thymeleaf的语法来动态渲染页面。`${message}`和`${name}`是变量,需要在控制器中设置它们的值。`th:action`属性指定了表单提交的URL。
3. 创建控制器
创建一个控制器来处理页面的请求和响应。例如:
```
@Controller
public class HomeController {
@GetMapping("/")
public String home(Model model) {
model.addAttribute("message", "Hello, world!");
model.addAttribute("name", "");
return "index";
}
@PostMapping("/submit")
public String submit(@RequestParam String name, Model model) {
model.addAttribute("message", "Hello, " + name + "!");
model.addAttribute("name", name);
return "index";
}
}
```
在上面的示例中,`home()`方法处理根路径的请求,设置`message`和`name`变量的值,并返回index模板。
`submit()`方法处理表单提交的请求,获取`name`参数的值,并设置`message`和`name`变量的值,然后返回index模板。
4. 运行应用程序
运行Spring Boot应用程序,访问http://localhost:8080/,即可看到渲染后的页面。在输入框中输入姓名并提交表单,即可看到页面上显示的消息会根据输入的姓名而变化。
以上就是使用Spring Boot和Thymeleaf实现HTML页面交互的简单示例。