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

ⅰ亾dé卋堺 提交于 2019-12-02 05:01:38

问题


In using Vaadin Flow, version 14, I know we can store state as key-value pairs kept as "attributes" via getAttribute/setAttribute/removeAttribute methods found on:

  • VaadinSession (per-user scope)
  • VaadinContext (web-app scope)

How does one access the current object for those classes?


回答1:


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() ) ;


来源:https://stackoverflow.com/questions/58036705/get-current-vaadincontext-and-current-vaadinsession-both-places-to-store-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!