问题
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