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

Steps…

  • 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

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 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

Advertisements

About Abhishek

Loves Java EE, distributed KV stores and messaging systems. Frequently blogs at abhirockzz.wordpress.com as well as simplydistributed.wordpress.com. Oh, I have also authored a few (mini) books, articles, Refcards etc. :-)
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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s