【问题标题】:Get current VaadinContext and current VaadinSession (both places to store state as "attribute" key-value pairs) in Vaadin Flow在 Vaadin Flow 中获取当前 VaadinContext 和当前 VaadinSession(这两个地方都将状态存储为“属性”键值对)
【发布时间】:2019-09-21 01:55:43
【问题描述】:

在使用 Vaadin Flow 版本 14 时,我知道我们可以通过以下位置的 getAttribute/setAttribute/removeAttribute 方法将状态存储为键值对并保存为“属性”:

如何访问这些类的当前对象?

【问题讨论】:

标签: session vaadin instance key-value vaadin-flow


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2023-03-05
    • 2013-07-30
    相关资源
    最近更新 更多