在Vaadin流中获取当前VaadinContext和当前VaadinSession(这两个位置都将状态存储为“属性”键值对)
在使用Vaadin Flow版本14时,我知道我们可以通过在Vaadin流中获取当前VaadinContext和当前VaadinSession(这两个位置都将状态存储为“属性”键值对),session,vaadin,instance,key-value,vaadin-flow,Session,Vaadin,Instance,Key Value,Vaadin Flow,在使用Vaadin Flow版本14时,我知道我们可以通过getAttribute/setAttribute/removeAttribute方法将状态存储为保留为“属性”的键值对,这些方法位于: (每个用户范围) (web应用程序范围) 如何访问这些类的当前对象?VaadinSession.getCurrent()➙ 语音会话 对于每个用户作用域,类提供了一个静态类方法来访问当前实例 VaadinSession session = VaadinSession.getCurrent() ;
getAttribute
/setAttribute
/removeAttribute
方法将状态存储为保留为“属性”的键值对,这些方法位于:
- (每个用户范围)
- (web应用程序范围)
VaadinSession.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()
➙ <代码>上下文
对于web应用程序的广域范围,您必须跳过一个额外的环。这个类实际上代表了整个web应用程序。但它将属性特性委托给类,该类的实例由当前服务实例跟踪。所以,用它来
VaadinServlet.getCurrent().getServletContext()
➙ <代码>ServletContext
上面讨论的VaadinContext
对象确实提供了web应用程序范围,可以将对象保存为键值映射中的“属性”。但是,请注意,的键必须是类
。有时,字符串
键可能工作得更好
如果希望在web应用程序中使用基于字符串的键值映射,请使用标准。该接口在标准中定义。、和方法都使用String
作为键,使用Object
作为值
ServletContext servletContext = VaadinServlet.getCurrent().getServletContext() ;
将对象存储为属性
servletContext.setAttribute( "map_of_department_to_manager" , map ) ;
由于该值不使用,因此在访问存储值时必须强制转换
Map< Department , Manager > map =
( Map< Department , Manager > ) // Casting from `Object`.
servletContext.getAttribute( "map_of_department_to_manager" )
;
检索
ServiceLocator serviceLocator =
( ServiceLocator ) // Must cast the retrieved object.
servletContext.getAttribute(
ServiceLocator.class.getCanonicalName() // Using name of class as our `String` key.
)
;
相关的:
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.
)
;