在Spring Boot中,可以使用Thymeleaf模板引擎和AJAX来实现前后端的分离和交互。以下是一个简单的例子:
- 添加依赖到
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 创建一个Controller返回数据:
@Controller
public class AjaxController {
@GetMapping("/greeting")
@ResponseBody
public Map<String, String> greeting(@RequestParam(name="name", required=false, defaultValue="World") String name) {
Map<String, String> model = new HashMap<>();
model.put("name", name);
return model;
}
}
- 创建Thymeleaf模板
greeting.html
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>AJAX in Spring Boot with Thymeleaf</title>
<script th:src="@{https://code.jquery.com/jquery-3.5.1.min.js}"></script>
</head>
<body>
<div id="greeting">
<p th:text="'Hello, ' + ${name} + '!'"></p>
</div>
<input type="text" id="name" placeholder="Type your name here" />
<button id="send">Send</button>
<script th:inline="javascript">
$('#send').click(function() {
var name = $('#name').val();
$.ajax({
url: /*[[@{/greeting}]]*/ '',
data: {name: name},
success: function(data) {
$('#greeting').html('Hello, ' + data.name + '!');
}
});
});
</script>
</body>
</html>
- 配置Spring Boot:
@SpringBootApplication
public class AjaxThymeleafApplication {
public static void main(String[] args) {
SpringApplication.run(AjaxThymeleafApplication.class, args);
}
}
- 配置Thymeleaf:
# application.properties
spring.thymeleaf.cache=false
以上代码实现了一个简单的AJAX请求,用户在输入框中输入名字,点击按钮后通过AJAX发送请求到后端,后端处理后返回数据,然后前端更新页面显示的内容。