Class VaadinSession
- All Implemented Interfaces:
jakarta.servlet.http.HttpSessionBindingListener,Serializable,EventListener
HttpSession, but others storage mechanisms
might also be used.
Everything inside a VaadinSession should be serializable to ensure
compatibility with schemes using serialization for persisting the session
data.
Current VaadinSession object which can be accessed by
getCurrent() is not present before VaadinServlet
starts handling the HTTP request. For example, it cannot be used in any
implementation of Filter interface.
- Since:
- 1.0
- Author:
- Vaadin Ltd
- See Also:
-
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionVaadinSession(VaadinService service) Creates a new VaadinSession tied to a VaadinService. -
Method Summary
Modifier and TypeMethodDescriptionProvides exclusive access to this session from outside a request handling thread.voidaccessSynchronously(Command command) Locks this session and runs the provided Command right away.voidaddRequestHandler(RequestHandler handler) Adds a request handler to this session.Adds a listener that gets notified when this session is destroyed.voidAdds an initialized UI to this session.voidPotentially checks whether this session is currently locked by the current thread, and fails with a standard error message if not.voidcheckHasLock(String message) Potentially checks whether this session is currently locked by the current thread, and fails with the given message if not.voidclose()Sets this session to be closed and all UI state to be discarded at the end of the current request, or at the end of the next request if there is no ongoing one.protected StreamResourceRegistryCreates the StreamResourceRegistry for this session.findElement(int uiId, int nodeId) Finds the given element in the session.static Collection<VaadinSession> getAllSessions(jakarta.servlet.http.HttpSession httpSession) Retrieves allVaadinSessions which are stored in the given HTTP session.<T> TgetAttribute(Class<T> type) Gets a stored attribute value.getAttribute(String name) Gets a stored attribute value.Get the web browser associated with this session.Gets the configuration for this session.longGets the total time spent servicing requests in this session.static VaadinSessionGets the currently used session.Gets the session's error handler.longGets the timestamp of the most recent lock operation performed on this session.longGets the time spent servicing the last request in this session.longReturns the time when the last request was serviced in this session.longGets the timestamp of the most recent unlock operation performed on this session.Gets the locale for this session.Gets theLockinstance that is used for protecting the data of this session from concurrent access.intCreates a new unique id for a UI.Gets the queue of tasks submitted usingaccess(Command).Gets the push connection identifier for this session.Gets the request handlers that are registered to the session.Get resource registry instance.Gets the underlying session to which this service session is currently associated.getState()Returns the lifecycle state of this session.getUIById(int uiId) Returns a UI with the given id.getUIs()Gets all the UIs of this session.booleanhasLock()Checks if the current thread has exclusive access to thisVaadinSession.protected static booleanhasLock(VaadinService service, WrappedSession session) Checks if the current thread has exclusive access to the given WrappedSession.voidlock()Locks this session to protect its data from concurrent access.voidrefreshTransients(WrappedSession wrappedSession, VaadinService vaadinService) Refreshes the transient fields of the session to ensure they are up to date.voidremoveRequestHandler(RequestHandler handler) Removes a request handler from the session.voidCalled by the framework to remove an UI instance from the session because it has been closed.<T> voidsetAttribute(Class<T> type, T value) Stores a value in this service session.voidsetAttribute(String name, Object value) Stores a value in this service session.voidsetBrowser(WebBrowser browser) Set the web browser associated with this session.static voidsetCurrent(VaadinSession session) Sets the thread local for the current session.voidsetErrorHandler(ErrorHandler errorHandler) Sets the session error handler.voidsetLastRequestDuration(long time) Sets the time spent servicing the last request in the session and updates the total time spent servicing requests in this session.voidsetLastRequestTimestamp(long timestamp) Sets the time when the last UIDL request was serviced in this session.voidSets the default locale for this session.protected voidsetState(VaadinSessionState state) Sets the lifecycle state of this session.voidunlock()Unlocks this session.voidvalueBound(jakarta.servlet.http.HttpSessionBindingEvent arg0) voidvalueUnbound(jakarta.servlet.http.HttpSessionBindingEvent event)
-
Field Details
-
browser
-
-
Constructor Details
-
VaadinSession
Creates a new VaadinSession tied to a VaadinService.- Parameters:
service- the Vaadin service for the new session
-
-
Method Details
-
createStreamResourceRegistry
Creates the StreamResourceRegistry for this session.- Returns:
- A StreamResourceRegistry instance
-
valueBound
public void valueBound(jakarta.servlet.http.HttpSessionBindingEvent arg0) - Specified by:
valueBoundin interfacejakarta.servlet.http.HttpSessionBindingListener- See Also:
-
valueUnbound
public void valueUnbound(jakarta.servlet.http.HttpSessionBindingEvent event) - Specified by:
valueUnboundin interfacejakarta.servlet.http.HttpSessionBindingListener- See Also:
-
getBrowser
Get the web browser associated with this session.- Returns:
- the web browser object
-
setBrowser
Set the web browser associated with this session.- Parameters:
browser- the web browser object
-
getCumulativeRequestDuration
public long getCumulativeRequestDuration()Gets the total time spent servicing requests in this session.- Returns:
- The total time spent servicing requests in this session, in milliseconds.
-
setLastRequestDuration
public void setLastRequestDuration(long time) Sets the time spent servicing the last request in the session and updates the total time spent servicing requests in this session.- Parameters:
time- The time spent in the last request, in milliseconds.
-
getLastRequestDuration
public long getLastRequestDuration()Gets the time spent servicing the last request in this session.- Returns:
- The time spent servicing the last request in this session, in milliseconds.
-
setLastRequestTimestamp
public void setLastRequestTimestamp(long timestamp) Sets the time when the last UIDL request was serviced in this session.- Parameters:
timestamp- The time when the last request was handled, in milliseconds since the epoch.
-
getLastRequestTimestamp
public long getLastRequestTimestamp()Returns the time when the last request was serviced in this session.- Returns:
- The time when the last request was handled, in milliseconds since the epoch.
-
getSession
Gets the underlying session to which this service session is currently associated.- Returns:
- the wrapped session for this context
-
getAllSessions
public static Collection<VaadinSession> getAllSessions(jakarta.servlet.http.HttpSession httpSession) Retrieves allVaadinSessions which are stored in the given HTTP session.- Parameters:
httpSession- the HTTP session- Returns:
- the found VaadinSessions
-
getConfiguration
Gets the configuration for this session. Delegates the call toVaadinService.getDeploymentConfiguration().- Returns:
- the deployment configuration
-
getLocale
Gets the locale for this session.The default locale is determined in different ways depending on whether a
I18NProvideris available.If a i18n provider is available, the locale is determined by selecting the locale from
I18NProvider.getProvidedLocales()that best matches the user agent preferences (i.e. theAccept-Languageheader). If an exact match is found, then that locale is used. Otherwise, the matching logic looks for the first provided locale that uses the same language regardless of the country. If no other match is found, then the first item fromI18NProvider.getProvidedLocales()is used.If no i18n provider is available, then the
default JVM localeis used as the default locale.- Returns:
- the locale of this session.
-
setLocale
Sets the default locale for this session.Setting the locale of a session will also override any custom locale configured for all UIs in this session.
- Parameters:
locale- the locale to set, notnull
-
getErrorHandler
Gets the session's error handler.- Returns:
- the current error handler
-
setErrorHandler
Sets the session error handler.- Parameters:
errorHandler- the new error handler, notnull
-
addRequestHandler
Adds a request handler to this session. Request handlers can be added to provide responses to requests that are not handled by the default functionality of the framework.Handlers are called in reverse order of addition, so the most recently added handler will be called first.
- Parameters:
handler- the request handler to add- See Also:
-
removeRequestHandler
Removes a request handler from the session.- Parameters:
handler- the request handler to remove
-
getRequestHandlers
Gets the request handlers that are registered to the session. The iteration order of the returned collection is the same as the order in which the request handlers will be invoked when a request is handled.- Returns:
- a collection of request handlers, with the iteration order according to the order they would be invoked
- See Also:
-
addSessionDestroyListener
Adds a listener that gets notified when this session is destroyed.This session will be locked and its
UIs will have been removed when the listener is called.If this session is already closed, no notification is delivered.
This method only delivers notifications for this session. To also be notified about other sessions, use
VaadinService.addSessionDestroyListener(com.vaadin.flow.server.SessionDestroyListener).- Parameters:
listener- the session destroy listener- Returns:
- a handle that can be used for removing the listener
- See Also:
-
getCurrent
Gets the currently used session. The current session is automatically defined when processing requests to the server (seeThreadLocal) and inaccess(Command)andUI.access(Command). In other cases, (e.g. from background threads), the current session is not automatically defined.The session is stored using a weak reference to avoid leaking memory in case it is not explicitly cleared.
- Returns:
- the current session instance if available, otherwise
null - See Also:
-
setCurrent
Sets the thread local for the current session. This method is used by the framework to set the current session whenever a new request is processed and it is cleared when the request has been processed.The application developer can also use this method to define the current session outside the normal request handling and treads started from request handling threads, e.g. when initiating custom background threads.
The session is stored using a weak reference to avoid leaking memory in case it is not explicitly cleared.
- Parameters:
session- the session to set as current- See Also:
-
getUIs
Gets all the UIs of this session. This includes UIs that have been requested but not yet initialized. UIs that receive no heartbeat requests from the client are eventually removed from the session.- Returns:
- a collection of UIs belonging to this application
-
getUIById
Returns a UI with the given id.This is meant for framework internal use.
- Parameters:
uiId- The UI id- Returns:
- The UI with the given id or null if not found
-
hasLock
public boolean hasLock()Checks if the current thread has exclusive access to thisVaadinSession.- Returns:
- true if the thread has exclusive access, false otherwise
-
checkHasLock
Potentially checks whether this session is currently locked by the current thread, and fails with the given message if not.When production mode is enabled, the check is done according to the
lock check strategy. By default, the check is only done if assertions are also enabled: this is done to avoid the small performance impact of continuously checking the lock status.The check is always done when production mode is not enabled, using the
SessionLockCheckStrategy.THROWstrategy.- Parameters:
message- the error message to include when failing if the check is done and the session is not locked
-
checkHasLock
public void checkHasLock()Potentially checks whether this session is currently locked by the current thread, and fails with a standard error message if not.When production mode is enabled, the check is done according to the
lock check strategy. By default, the check is only done if assertions are also enabled: this is done to avoid the small performance impact of continuously checking the lock status.The check is always done when production mode is not enabled, using the
SessionLockCheckStrategy.THROWstrategy. -
hasLock
Checks if the current thread has exclusive access to the given WrappedSession.- Parameters:
service- the service to checksession- the session to use for checking- Returns:
- true if this thread has exclusive access, false otherwise
-
removeUI
Called by the framework to remove an UI instance from the session because it has been closed.- Parameters:
ui- the UI to remove
-
getLockInstance
Gets theLockinstance that is used for protecting the data of this session from concurrent access.The
Lockcan be used to gain more control than what is available only usinglock()andunlock(). The returned instance is not guaranteed to support any other features of theLockinterface thanLock.lock()andLock.unlock().- Returns:
- the
Lockthat is used for synchronization, it's nevernullfor the session which is in use, i.e. ifrefreshTransients(WrappedSession, VaadinService)has been called for it - See Also:
-
lock
public void lock()Locks this session to protect its data from concurrent access. Accessing the UI state from outside the normal request handling should always lock the session and unlock it when done. The preferred way to ensure locking is done correctly is to wrap your code usingUI.access(Command)(oraccess(Command)if you are only touching the session and not any UI), e.g.:myUI.access(new Command() { @Override public void run() { // Here it is safe to update the UI. // UI.getCurrent can also be used myUI.getContent().setCaption("Changed safely"); } });If you for whatever reason want to do locking manually, you should do it like:
session.lock(); try { doSomething(); } finally { session.unlock(); }This method will block until the lock can be retrieved.
getLockInstance()can be used if more control over the locking is required.- See Also:
-
unlock
public void unlock()Unlocks this session. This method should always be used in a finally block afterlock()to ensure that the lock is always released.For UIs in this session that have its push mode set to
automatic, pending changes will be pushed to their respective clients.- See Also:
-
setAttribute
Stores a value in this service session. This can be used to associate data with the current user so that it can be retrieved at a later point from some other part of the application. Setting the value tonullclears the stored value.- Parameters:
name- the name to associate the value with, can not benullvalue- the value to associate with the name, ornullto remove a previous association.- See Also:
-
setAttribute
Stores a value in this service session. This can be used to associate data with the current user so that it can be retrieved at a later point from some other part of the application. Setting the value tonullclears the stored value.The fully qualified name of the type is used as the name when storing the value. The outcome of calling this method is thus the same as if calling
setAttribute(type.getName(), value);- Type Parameters:
T- the type of the stored value- Parameters:
type- the type that the stored value represents, can not be nullvalue- the value to associate with the type, ornullto remove a previous association.- See Also:
-
getAttribute
Gets a stored attribute value. If a value has been stored for the session, that value is returned. If no value is stored for the name,nullis returned.- Parameters:
name- the name of the value to get, can not benull.- Returns:
- the value, or
nullif no value has been stored or if it has been set to null. - See Also:
-
getAttribute
Gets a stored attribute value. If a value has been stored for the session, that value is returned. If no value is stored for the name,nullis returned.The fully qualified name of the type is used as the name when getting the value. The outcome of calling this method is thus the same as if calling
getAttribute(type.getName());- Type Parameters:
T- the type of the value to get- Parameters:
type- the type of the value to get, can not benull.- Returns:
- the value, or
nullif no value has been stored or if it has been set to null. - See Also:
-
getNextUIid
public int getNextUIid()Creates a new unique id for a UI.- Returns:
- a unique UI id
-
addUI
Adds an initialized UI to this session.- Parameters:
ui- the initialized UI to add.
-
getService
-
close
public void close()Sets this session to be closed and all UI state to be discarded at the end of the current request, or at the end of the next request if there is no ongoing one.After the session has been discarded, any UIs that have been left open will give a Session Expired error and a new session will be created for serving new UIs.
Note that this method only closes the
VaadinSessionwhich is not the same asHttpSession. To invalidate the underlying HTTP sessiongetSession().invalidate();needs to be called.The method is usually called to perform logout. If user data is stored inside HTTP session then
getSession().invalidate();should be called instead (most common case). It makes sense to callclose()only if user data is stored inside aVaadinSession. Use thePage.setLocation(String)method to navigate to some page after session is closed to avoid session expired message.- See Also:
-
getState
Returns the lifecycle state of this session.- Returns:
- the current state
-
setState
Sets the lifecycle state of this session. The allowed transitions are OPEN to CLOSING and CLOSING to CLOSED.- Parameters:
state- the new state
-
accessSynchronously
Locks this session and runs the provided Command right away.It is generally recommended to use
access(Command)instead of this method for accessing a session from a different thread asaccess(Command)can be used while holding the lock of another session. To avoid causing deadlocks, this methods throws an exception if it is detected than another session is also locked by the current thread.This method behaves differently than
access(Command)in some situations:- If the current thread is currently holding the lock of this session,
accessSynchronously(Command)runs the task right away whereasaccess(Command)defers the task to a later point in time. - If some other thread is currently holding the lock for this session,
accessSynchronously(Command)blocks while waiting for the lock to be available whereasaccess(Command)defers the task to a later point in time.
- Parameters:
command- the command which accesses the session- Throws:
IllegalStateException- if the current thread holds the lock for another session- See Also:
- If the current thread is currently holding the lock of this session,
-
access
Provides exclusive access to this session from outside a request handling thread.The given command is executed while holding the session lock to ensure exclusive access to this session. If this session is not locked, the lock will be acquired and the command is run right away. If this session is currently locked, the command will be run before that lock is released.
RPC handlers for components inside this session do not need to use this method as the session is automatically locked by the framework during RPC handling.
Please note that the command might be invoked on a different thread or later on the current thread, which means that custom thread locals might not have the expected values when the command is executed.
getCurrent()andVaadinService.getCurrent()are set according to this session before executing the command. Other standard CurrentInstance values such asVaadinService.getCurrentRequest()andVaadinService.getCurrentResponse()will not be defined.The returned future can be used to check for task completion and to cancel the task. To help avoiding deadlocks,
Future.get()throws an exception if it is detected that the current thread holds the lock for some other session.- Parameters:
command- the command which accesses the session- Returns:
- a future that can be used to check for task completion and to cancel the task
- See Also:
-
getPendingAccessQueue
Gets the queue of tasks submitted usingaccess(Command). It is safe to call this method and access the returned queue without holding thesession lock.- Returns:
- the queue of pending access tasks
-
getPushId
Gets the push connection identifier for this session. Used when establishing a push connection with the client.- Returns:
- the push connection identifier string
-
refreshTransients
Refreshes the transient fields of the session to ensure they are up to date.Called internally by the framework.
- Parameters:
wrappedSession- the session this VaadinSession is stored invaadinService- the service associated with this VaadinSession
-
getResourceRegistry
Get resource registry instance.Use this instance to manage
StreamResources.- Returns:
- resource registry
-
getLastLocked
public long getLastLocked()Gets the timestamp of the most recent lock operation performed on this session.Value is expressed as the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
- Returns:
- last lock operation timestamp.
-
getLastUnlocked
public long getLastUnlocked()Gets the timestamp of the most recent unlock operation performed on this session.Value is expressed as the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
- Returns:
- last unlock operation timestamp.
-
findElement
Finds the given element in the session.The ids are typically acquired in the browser using
getUiId()andgetNodeId(element)available in thewindow.Vaadin.Flow.clientsvalue.- Parameters:
uiId- The UI idnodeId- the node id- Returns:
- the element instance
- Throws:
IllegalArgumentException- if the element was not found
-