能否在Mustache中调用Spring Boot的REST API接口?
当然可以实现!其实Mustache本身是模板引擎,主要负责渲染页面的基础结构和初始数据,但要调用REST API获取动态数据,你需要结合前端JavaScript来发起HTTP请求——毕竟模板引擎只在服务器端完成首次渲染,后续的动态数据交互还是得靠前端的AJAX/Fetch API。
下面我给你一套完整的代码示例,带你快速实现这个方案:
1. 核心思路
Spring Boot 负责两部分:
- 用
RestController提供REST API接口,返回JSON格式的数据 - 用普通
Controller返回Mustache模板页面
前端部分:页面加载后,通过JS调用REST API获取数据,再用Mustache渲染这些数据到页面上
2. 代码实现
第一步:编写REST API控制器
先创建一个处理用户数据的RestController,模拟返回用户列表和单个用户信息:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("/api/users") public class UserRestController { // 获取所有用户列表的接口 @GetMapping public List<User> getAllUsers() { // 实际项目中这里替换为数据库查询逻辑 return Arrays.asList( new User(1L, "张三", "zhangsan@example.com"), new User(2L, "李四", "lisi@example.com") ); } // 根据ID获取单个用户的接口 @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { // 实际项目中根据ID查询数据库 return new User(id, "张三", "zhangsan@example.com"); } // 内部用户实体类 public static class User { private Long id; private String name; private String email; public User(Long id, String name, String email) { this.id = id; this.name = name; this.email = email; } // Getter方法,JSON序列化需要 public Long getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } } }
第二步:编写Mustache模板页面
在src/main/resources/templates下创建users.mustache文件,这里我们用Fetch API调用REST接口,然后用Mustache渲染数据:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>用户列表</title> <style> .user-item { border: 1px solid #eee; padding: 12px; margin: 8px 0; border-radius: 4px; } button { margin-top: 8px; padding: 4px 8px; cursor: pointer; } </style> </head> <body> <h2>用户目录</h2> <div id="user-container"></div> <script> // 页面加载完成后发起API请求 document.addEventListener('DOMContentLoaded', async () => { try { // 调用REST接口获取用户列表 const response = await fetch('/api/users'); if (!response.ok) { throw new Error(`请求失败:${response.status}`); } const users = await response.json(); // 定义Mustache模板片段 const userTemplate = ` <div class="user-item"> <h3>{{name}}</h3> <p>邮箱:{{email}}</p> <button onclick="showUserDetail({{id}})">查看详情</button> </div> `; // 遍历用户数据,用Mustache渲染每个用户的HTML const userHtml = users.map(user => Mustache.render(userTemplate, user)).join(''); document.getElementById('user-container').innerHTML = userHtml; } catch (err) { console.error('加载用户失败:', err); document.getElementById('user-container').innerHTML = '<p>加载用户列表失败,请稍后重试</p>'; } }); // 查看单个用户详情的函数 async function showUserDetail(userId) { try { const response = await fetch(`/api/users/${userId}`); const user = await response.json(); alert(`用户详情:\nID:${user.id}\n姓名:${user.name}\n邮箱:${user.email}`); } catch (err) { console.error('获取用户详情失败:', err); alert('获取用户详情失败'); } } </script> <!-- 引入Mustache.js库,你也可以下载到本地引入 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/4.2.0/mustache.min.js"></script> </body> </html>
第三步:配置Spring Boot并编写页面控制器
首先在application.properties里配置Mustache的基础设置:
# Mustache模板文件的前缀和后缀 spring.mustache.prefix=classpath:/templates/ spring.mustache.suffix=.mustache # 开发环境关闭模板缓存,修改模板后无需重启服务 spring.mustache.cache=false
然后创建一个普通的Controller来返回Mustache页面:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class PageController { // 访问/users路径时返回users.mustache模板 @GetMapping("/users") public String usersPage() { // 这里不需要往model里传数据,因为数据由前端通过API获取 return "users"; } }
关键说明
- Mustache的角色:在这里它既可以渲染服务器端传入的初始数据,也可以配合前端JS渲染从API获取的动态数据,灵活性很高。
- 这种方案的优势:既保留了Mustache简洁的模板语法,又能通过REST API实现前后端松耦合,比传统的JSP/Servlet模式更符合现代Web开发的思路。
- 注意事项:要确保前端引入了Mustache.js库,否则无法调用
Mustache.render方法;生产环境建议把Mustache.js下载到本地,避免依赖外部CDN。
内容的提问来源于stack exchange,提问作者Jeka_FRI
相关产品推荐
相关产品推荐

