You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vaadin页面重载后无法显示Notification的问题排查与解决

问题原因及解决方案

问题出在哪?

你调用UI.getCurrent().getPage().reload()后,浏览器会立即开始刷新页面,当前页面的所有客户端代码执行都会被终止,后面的new Notification("Success", 5000).open()根本没有机会运行——因为页面重载后,原有的UI实例和客户端上下文已经被销毁,新的页面实例还未初始化,自然不会显示通知。

解决方法

以下是两种常用的实现方式,可根据场景选择:

方式一:使用浏览器sessionStorage存储状态

利用浏览器的sessionStorage在页面重载前标记需要显示通知,页面加载完成后检查标记并显示通知,最后清除标记避免重复触发。

  1. 触发页面重载的代码:
// 将需要显示通知的状态存入sessionStorage
UI.getCurrent().getPage().executeJs("sessionStorage.setItem('showSuccessNotify', '1')");
// 执行页面重载
UI.getCurrent().getPage().reload();
  1. 在UI或视图的初始化逻辑中检查并显示通知(比如重写onAttach方法):
@Override
protected void onAttach(AttachEvent attachEvent) {
    super.onAttach(attachEvent);
    // 读取sessionStorage中的标记
    UI.getCurrent().getPage().executeJs("return sessionStorage.getItem('showSuccessNotify');")
            .then(String.class, flag -> {
                if ("1".equals(flag)) {
                    // 显示通知
                    new Notification("Success", 5000).open();
                    // 清除标记,防止下次页面加载重复显示
                    UI.getCurrent().getPage().executeJs("sessionStorage.removeItem('showSuccessNotify')");
                }
            });
}

方式二:使用Vaadin Session存储状态

如果应用依赖Vaadin会话(Session),可以将状态存在Vaadin Session中,页面重载后读取该状态并显示通知。

  1. 触发页面重载的代码:
// 在Vaadin Session中标记需要显示通知
VaadinSession.getCurrent().setAttribute("showSuccessNotify", true);
// 执行页面重载
UI.getCurrent().getPage().reload();
  1. 在UI或视图的onAttach方法中检查并显示通知:
@Override
protected void onAttach(AttachEvent attachEvent) {
    super.onAttach(attachEvent);
    VaadinSession session = VaadinSession.getCurrent();
    // 读取Session中的标记
    Boolean needShowNotify = (Boolean) session.getAttribute("showSuccessNotify");
    if (Boolean.TRUE.equals(needShowNotify)) {
        // 显示通知
        new Notification("Success", 5000).open();
        // 移除标记,避免重复显示
        session.removeAttribute("showSuccessNotify");
    }
}

注意事项

  • sessionStorage是浏览器标签页独立的,适合单标签页场景;Vaadin Session是会话级共享的,多标签页场景下可能会出现跨标签触发通知的情况,需根据业务需求选择。
  • 无论哪种方式,都要记得在显示通知后清除标记,防止页面再次加载时重复显示通知。

内容的提问来源于stack exchange,提问作者Felix Schildmann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 17:47:08