Get current VaadinContext and current VaadinSession (both places to store state as “attribute” key-value pairs) in Vaadin Flow

孤人 提交于 2019-12-02 00:44:29

VaadinSession.getCurrent()

For that per-user scope, the VaadinSesion class provides a static class method getCurrent to access the current instance.

VaadinSession session = VaadinSession.getCurrent() ;   // Fetch current instance of `VaadinSession` to use its key-value collection of attributes.
session.setAttribute( User.class , user ) ;            // Register user's successful authentication.

VaadinService.getCurrent().getContext()

For that web-app-wide scope, you must jump through one extra hoop. The VaadinService class actually represents the web app as a whole. But it delegates the attributes feature to the VaadinContext class, an instance of which is tracked by the current service instance. So get the service, and use that to get the context.

VaadinContext context = VaadinService.getCurrent().getContext() ;  // Get the current `VaadinService` object, and ask it for the current `VaadinSession` object.
context.setAttribute( ServiceLocator.class , new ServiceLocatorForTesting() ) ;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!