It’s possible to obtain a reference to the HttpSession
within a WebSocket application using a custom implementation of ServerEndpointConfig.Configurator
Here is an example application on Github
Steps…
- Override the
modifyHandshakeRequest
method - call the
getHttpSession
method on theHandshakeRequest
object which is passed into the method by the WebSocket runtime - store it – one possible option is to use the
Map
provided by theServerEndpointConfig
object (via the methodgetUserProperties
)
This map can then be accessed within the @OnOpen
callback (in case of an annotated @ServerEndpoint
implementation) using the EndpointConfig
object which is passed in automatically by the WebSocket runtime
Caveat
The WebSocket implementation does not create a Http Session, it just asks for one if it exists. Don’t be surprised if you find a null
HttpSession
in your configurator method. To have the session created for, you would need to call getSession
in HttpSession
from within a servlet Filter
or ServletRequestListener
Check the README for more details
Other things to know…
- By default, the WebSocket implementation does not handle the life cycle of
Http
andWebSocket
sessions together i.e. it is possible for theHttpSession
to end but the WebSocketSession
to stay alive.. unless… - access to the client initiating the WebSocket connection is protected, the WebSocket implementation makes sure that the associated WebSocket
Session
is terminated along with the HTTP session