Get current VaadinContext and current VaadinSessio

2020-04-16 04:06发布

问题:

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

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

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

VaadinServlet.getCurrent().getServletContext()ServletContext

The VaadinContext object discussed above does provide web-app-wide scope for saving objects as "attributes" in a key-value mapping. However, notice that the key to must be a Class. Sometimes a String key might work better.

If you want a String-based key-value mapping across your web app, use the standard ServletContext. This interface is defined in the Jakarta Servlet standard. The setAttribute, getAttribute, removeAttribute, and getAttributeNames() methods all use String as the key, and Object as the value.

ServletContext servletContext = VaadinServlet.getCurrent().getServletContext() ;

Store your object as an attribute.

servletContext.setAttribute( "map_of_department_to_manager" , map ) ;

Since the value does not use Java Generics, we must cast when accessing a stored value.

Map< Department , Manager > map = 
    ( Map< Department , Manager > )  // Casting from `Object`. 
    servletContext.getAttribute( "map_of_department_to_manager" )
;

If you do have only a single object of a particular class to store, you can use the class name as the string-based key.

servletContext.setAttribute( 
    ServiceLocator.class.getCanonicalName() , 
    new ServiceLocatorForTesting() 
) ;

Retrieval.

ServiceLocator serviceLocator = 
    ( ServiceLocator )                           // Must cast the retrieved object. 
    servletContext.getAttribute( 
        ServiceLocator.class.getCanonicalName()  // Using name of class as our `String` key.
    ) 
;