在 Spring Boot 中,前端挂载(Mounting Frontend)通常指将前端组件或页面嵌入到后端的 Web 应用程序中。这样做可以让前端与后端紧密集成,并提供更好的用户体验。
在 Spring Boot 中实现前端挂载的方法包括:
1. 使用 Thymeleaf 渲染 HTML 页面,然后将页面嵌入到后端的控制器中。
2. 使用 Vue.js、React 等前端框架创建单页应用程序(SPA),然后将打包后的 JS 和 CSS 文件放置在后端的静态资源目录下,在后端的控制器中返回 index.html 页面来启动 SPA。
以下是一个简单的代码示例,演示了如何使用 Thymeleaf 将前端组件嵌入到后端的控制器中:
1. 创建一个名为 `hello.html` 的 Thymeleaf 模板文件,其中包含一个按钮和一个显示文本的区域:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<button οnclick="sayHello()">Say Hello</button>
</div>
<div th:id="message">Message will appear here</div>
<script th:inline="javascript">
function sayHello() {
/* 发送 AJAX 请求到服务器获取消息 */
fetch('/api/message')
.then(response => response.text())
.then(message => {
/* 显示消息 */
document.getElementById('message').textContent = message;
});
}
</script>
</body>
</html>
```
2. 创建一个名为 `HelloController` 的后端控制器,在该控制器中将 Thymeleaf 模板渲染为 HTML 页面:
```
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
/* 将模板所需的数据传递给模板 */
model.addAttribute("name", "world");
/* 渲染 Thymeleaf 模板为 HTML 页面 */
return "hello";
}
}
```
3. 启动应用程序,访问 `http://localhost:8080/hello` 即可看到渲染后的页面。用户点击按钮时,前端组件会向服务器发送 AJAX 请求,获取消息并将其显示在页面上。