Accessing HTTP Session in WebSocket endpoint

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


  • Override the modifyHandshakeRequest method
  • call the getHttpSession method on the HandshakeRequest object which is passed into the method by the WebSocket runtime
  • store it – one possible option is to use the Map provided by the ServerEndpointConfig object (via the method getUserProperties)

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


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 and WebSocket sessions together i.e. it is possible for the HttpSession to end but the WebSocket Session 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

Further reading


About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java EE and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s