How can I get the cookie value inside the websocket endpoint

I am using JavaEE 7 based Websocket-API in my application.

I need to access the values โ€‹โ€‹set in cookies inside my websocket endpoint [Annotated one : @ServerEndpoint ("/websocket") ] . How can I do it?

@onOpen() there is a method that will be called automatically when a connection is established with this websocket endpoint. I want to get cookie values โ€‹โ€‹inside this method.

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

Please help me do this. Thanks in advance.

+6
source share
2 answers

Request parameters are accessed using the @ServerEndpoint(configurator=MyConfigurator.class) method @ServerEndpoint(configurator=MyConfigurator.class) .

See another answer on how to access HttpSession , as its methods are very similar.

+6
source

Although Joachimโ€™s answer gives a hint in the right direction, I believe that he doesnโ€™t fully answer the question or, at least, can be supplemented.

To get a cookie value, you must get the headers of the HandshakeRequest object and look at the header with the name cookie. Your modifyHandshake implementation will look something like this:

 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")); } } 
+8
source

Source: https://habr.com/ru/post/951199/


All Articles