7

I'm using Websocket-API based on JavaEE 7, in my application.

I'm required to access the values set in cookies inside my websocket endpoint [Annotated one : @ServerEndpoint ("/websocket") ]. How would I do that?

@onOpen() method is there, which will be called automatically when a connection to this websocket endpoint is established. I want to access cookies values in there, inside this method.

I know how to do that in a servlet or JSP, but I'm new to Websockets.

Please help me doing this. Thanks in advance.

Aryan Venkat
  • 679
  • 1
  • 10
  • 34

2 Answers2

10

While Joakim's answer does provide a hint in the right direction I believe it does not fully answer the question, or at least can be complemented.

In order to retrieve the value of a cookie you must get the headers of the HandshakeRequest object, and look for the header named "cookie". Your modifyHandshake implementation will look something like:

public class MyEndpointConfigurator extends ServerEndpointConfig.Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig config, 
                                HandshakeRequest request, 
                                HandshakeResponse response)
    {
        Map<String,List<String>> headers = request.getHeaders();
        config.getUserProperties().put("cookie",headers.get("cookie"));
    }
}
gabouy
  • 755
  • 1
  • 7
  • 16
6

Access to request parameters is done via the @ServerEndpoint(configurator=MyConfigurator.class) technique.

See other answer on how to access the HttpSession, as its techniques are very similar.

Community
  • 1
  • 1
Joakim Erdfelt
  • 46,896
  • 7
  • 86
  • 136
  • That's really wonderful. I can successfully get HttpSession using the way you've illustrated. But my intention is to get the cookies, not HttpSession; I tried the same scenario, but failed to get it. 'this.httpCookie = (HttpSession) config.getUserProperties() .get(HttpCookie.class.getName());' I don't know how to put this HttpCookie into EndPointConfig, thru modifyHandshake() method of the Configurator. Help me doing this. – Aryan Venkat Aug 07 '13 at 13:31
  • This doesn't actually answer the original question – gshauger Jul 24 '14 at 17:11
  • @gshauger this was really a duplicate question, hence the reference to the other answer on accessing the HttpSession (where Cookies are traditionally accessed from in JEE applications) – Joakim Erdfelt Jul 29 '14 at 01:25
  • @JoakimErdfelt Thanks for the link to the other answer. There is a wealth of information there. – isapir Sep 12 '16 at 17:40