由于WebSocket與Http協(xié)議的不同,故在使用常用的HttpSession方面就存在了一些問題。通過google翻閱到了在onOpen方法下使用HttpSession的方法。 新建一個GetHttpSessionConfigurator類并繼承Configurator類 package per.zww.web; import javax.servlet.http.HttpSession; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; import javax.websocket.server.ServerEndpointConfig.Configurator; /* * 獲取HttpSession * */ public class GetHttpSessionConfigurator extends Configurator { @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { // TODO Auto-generated method stub HttpSession httpSession=(HttpSession) request.getHttpSession(); sec.getUserProperties().put(HttpSession.class.getName(),httpSession); } } 然后在@ServerEndpoint注解里面添加configurator屬性 @ServerEndpoint(value="/socketTest",configurator=GetHttpSessionConfigurator.class)
在onOpen方法里加入?yún)?shù)EndpointConfig config即可獲取HttpSession @OnOpen public void onOpen(Session session,EndpointConfig config) { HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName()); System.out.println( httpSession.getAttribute("name")); sessionMap.put(session.getId(), session); }
|
|