VaadinSession.getCurrent() ➙ VaadinSession
对于那个每用户范围,VaadinSesion 类提供了一个静态类方法getCurrent 来访问当前实例。
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
对于 web-app-wide 范围,您必须多跳一圈。 VaadinService 类实际上代表了整个 Web 应用程序。但它将 attributes 功能委托给 VaadinContext 类,当前服务实例跟踪该类的实例。所以get the service,然后用它来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
上面讨论的VaadinContext 对象确实为将对象保存为键值映射中的“属性”提供了网络应用范围的范围。但是,请注意,密钥必须是Class。有时String 键可能会更好。
如果您希望在您的 Web 应用程序中使用基于字符串的键值映射,请使用标准 ServletContext。此接口在Jakarta Servlet 标准中定义。 setAttribute、getAttribute、removeAttribute和getAttributeNames()方法都使用String作为键,Object作为值。
ServletContext servletContext = VaadinServlet.getCurrent().getServletContext() ;
将您的对象存储为属性。
servletContext.setAttribute( "map_of_department_to_manager" , map ) ;
由于该值不使用Java Generics,因此我们必须在访问存储值时进行强制转换。
Map< Department , Manager > map =
( Map< Department , Manager > ) // Casting from `Object`.
servletContext.getAttribute( "map_of_department_to_manager" )
;
如果您确实只有一个特定类的对象要存储,则可以使用类名作为基于字符串的键。
servletContext.setAttribute(
ServiceLocator.class.getCanonicalName() ,
new ServiceLocatorForTesting()
) ;
检索。
ServiceLocator serviceLocator =
( ServiceLocator ) // Must cast the retrieved object.
servletContext.getAttribute(
ServiceLocator.class.getCanonicalName() // Using name of class as our `String` key.
)
;