WebSocket's writing is not much to say, it is important to remember the problems that arise
1. Cannot get to HttpSession
Workaround: First override the handshake method and put HttpSession in the map returned by the Serverendpointconfig.getuserproperties () method
1 Importjavax.servlet.http.HttpSession;2 ImportJavax.websocket.HandshakeResponse;3 Importjavax.websocket.server.HandshakeRequest;4 ImportJavax.websocket.server.ServerEndpointConfig;5 ImportJavax.websocket.server.ServerEndpointConfig.Configurator;6 7 /**8 * Inherit the WebSocket configuration class and put the httpsession into the Serverendpointconfig map9 * so that objects in the httpsession can be accessed by the WebSocket objectTen */ One Public classGethttpsessionconfiguratorextendsconfigurator{ A - /** - * Override Modify Handshake method the * @paramsec - * @paramRequest - * @paramResponse - */ + @Override - Public voidModifyhandshake (serverendpointconfig sec, handshakerequest request, handshakeresponse response) { +HttpSession HttpSession =(HttpSession) request.gethttpsession (); ASec.getuserproperties (). put (HttpSession.class. GetName (), httpSession); at } -}
Then add the Configurator configuration to the annotations @serverendpoint
1 @ServerEndpoint (value= "/websocket", Configurator=gethttpsessionconfigurator. Class)
It is now possible to get to httpsession.
However, if I do not log in, but need to temporarily login this situation? According to the above demo, you will find that there is no way to connect, has been close state
The following is a solution to this problem
2, not logged in user connection WebSocket, has been close status of the situation resolved:
The workaround is to create a request listener
1 @WebListener2 Public classRequestlistenerImplementsServletrequestlistener {3 4 Public voidrequestinitialized (servletrequestevent SRE) {5 //bring all request requests to the HttpSession6 ( (HttpServletRequest) sre.getservletrequest ()). GetSession ();7 8 }9 PublicRequestlistener () {Ten //TODO auto-generated Constructor stub One } A - Public voidrequestdestroyed (servletrequestevent arg0) { - //TODO auto-generated Method Stub the } -}
Problem solving.
"Summary" Java uses websocket to get httpsession problems