
本文介绍如何在不依赖第三方消息中间件的前提下,将 servlet 层产生的数据或事件安全、可靠地传递至 zk 的 mvvm 层,重点讲解基于 http session 共享数据和使用 session 范围事件队列触发 ui 响应的两种核心方案。
本文介绍如何在不依赖第三方消息中间件的前提下,将 servlet 层产生的数据或事件安全、可靠地传递至 zk 的 mvvm 层,重点讲解基于 http session 共享数据和使用 session 范围事件队列触发 ui 响应的两种核心方案。
在 ZK 应用中,Servlet 与 MVVM 层通常处于不同执行上下文:Servlet 运行于标准 Java EE 请求线程,而 ZK ViewModel 依赖于 ZK 的 Execution(如 Desktop 或 Session)环境。因此,直接调用 ViewModel 方法或触发桌面级事件队列(DesktopScope)不可行——因为 HttpServlet 无法获取当前 Desktop 实例。
✅ 推荐方案一:通过 HttpSession 共享状态(适用于数据传递)
这是最轻量、最兼容的方式。Servlet 将处理结果存入当前用户的 HttpSession,ZK ViewModel 在绑定时或响应用户操作时主动读取:
// 在 Servlet 中(例如 doPost)
HttpSession session = request.getSession(true);
session.setAttribute("userNotification", "订单已提交,等待审核");
session.setAttribute("pendingOrderId", 12345L);// 在 ZK ViewModel 中(需实现 Initializable 或监听属性变化)
public class MainViewModel implements Initializable {
private String notification;
private Long pendingOrderId;
@Override
public void doAfterCompose(@Nullable Component comp) throws Exception {
HttpSession session = Sessions.getCurrent().getNativeSession();
this.notification = (String) session.getAttribute("userNotification");
this.pendingOrderId = (Long) session.getAttribute("pendingOrderId");
// 清理一次性数据(可选)
session.removeAttribute("userNotification");
session.removeAttribute("pendingOrderId");
}
// 提供 getter 供 ZUL 绑定
public String getNotification() { return notification; }
public Long getPendingOrderId() { return pendingOrderId; }
}? 注意事项:
-
Sessions.getCurrent().getNativeSession()可安全获取与当前 ZK Session 关联的HttpSession; - 数据仅对当前用户会话有效,天然具备隔离性;
- 避免存储大对象或非序列化类型,以防集群环境下 Session 复制失败。
✅ 推荐方案二:使用 Session-scoped Event Queue(适用于事件驱动通知)
当需要“主动推送”而非“被动拉取”时(例如:后台任务完成需实时刷新 UI),应使用 Session 范围的事件队列。它不要求 Execution,可在 Servlet 中通过 WebApps.getCurrent().getEventQueue() 获取并发布事件:
// 在 Servlet 中(确保 WebApps 已初始化)
EventQueue<Event> eq = WebApps.getCurrent()
.getEventQueue("uiNotifications", EventQueue.SESSION_SCOPE);
eq.publish(new Event("onDataReady", null,
Map.of("status", "success", "dataId", 789)));<!-- 在 ZUL 页面中声明监听 -->
<window apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('com.example.MainViewModel')">
<div>
<label value="@load(vm.notification)" />
<!-- 其他组件 -->
</div>
</window>// ViewModel 中监听 Session 事件队列
public class MainViewModel implements NotifyChangeHandler {
private String notification = "";
@NotifyChange("notification")
public void onEvent(Event event) {
if ("onDataReady".equals(event.getName())) {
Map<?, ?> data = (Map<?, ?>) event.getData();
this.notification = "新数据就绪: ID=" + data.get("dataId");
}
}
// 在 ZUL 中绑定:onNotifyChange="@notifyChange('notification')"
}⚠️ 关键限制与最佳实践:
- 不要使用
DesktopScope事件队列——Servlet 无Desktop上下文; -
SessionScope事件队列自动绑定到当前HttpSession,无需手动管理生命周期; - 事件发布与消费需确保事件名称一致,且 ViewModel 必须在对应 Session 的 ZK 页面中已注册监听;
- 若应用部署在多节点集群,需确保
HttpSession粘性或启用分布式 Session(如 Redis),否则事件可能丢失。
综上,数据共享优先选 HttpSession 属性,事件通知优先选 Session-scoped EventQueue——二者组合可覆盖绝大多数 Servlet → ZK MVVM 的集成场景,零外部依赖,符合 ZK 原生设计哲学。

















