Vaadin Session Management - How does it work?

守給你的承諾、 提交于 2019-12-04 17:06:46

If in Vaadin 8, you have simple hierarchy of scope, on three levels.

  • ServletContext
    Represents your entire Vaadin web app.
  • VaadinSession
    Represents each user's work session.
  • UI
    Represents each web browser/tab within a session (Vaadin supports multi-window apps, pretty amazing).

The first is a standard part of every Java Servlet, defined in the spec.

The second is a wrapper around the session, also defined in the Java Servlet spec.

Vaadin is actually one huge Servlet, so it carries these features of context and session.

The UI class is unique to Vaadin. It represents the content of a web browser window/tab. Vaadin supports multi-window apps, tracking all the open windows/tabs as part of the session, a very nice feature of Vaadin.

To store state-wide app, use the standard ServletContext object. It carries a key-value collection known as "attributes". The key is of String type, and the value is of Object type. Call methods setAttribute, getAttribute, and removeAttribute. Use this collection for any objects you may need to access for any of your users, accoss their sessions. You may to learn about ServletContextListener by the way, to hook into your web app launching and exiting.

The VaadinSession class carries the same kind of key-value collection, with similar "attribute" methods. Use this to track items throughout the user’s work session, across them possibly opening/colsing multiple windows/tabs of your app. For example, in the session you would store the user’s Spirit Animal choice, their avatar image, and the fact that person has been authenticated via username/password credentials. See this page in the manual, Setting and reading session attributes.

If you want to store per-window settings, for something like their choice of background color or light/dark mode, store something on UI. Unfortunately, that class does not come with a convenient key-value store that I know of. So you'll need to add your own Map, or some other member variables to your UI subclass.

For more info, see my Answer to a similar Question. I made some nifty diagrams there. That question is about Vaadin 7, but as I vaguely recall, these concepts carry over between 7 and 8.

As for VaadinService and VaadinServletService, I have never understood exactly their role. They seem to represent various aspects of your entire Vaadin web at runtime. But neither carries a convenient key-value collection as like VaadinSession. (If you use Vaadin Flow, versions 10+, see VaadinContext, a class than does represent your entire web app, and does carry a convenient key-value collection of "attributes".)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!