WebSocket之获取HttpSession_html/css_WEB-ITnose

WBOY
Release: 2016-06-21 09:00:22
Original
1399 people have browsed it

WebSocket之获取HttpSession

由于WebSocket与Http协议的不同,故在使用常用的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);    }    }
Copy after login

然后在@ServerEndpoint注解里面添加configurator属性

@ServerEndpoint(value="/socketTest",configurator=GetHttpSessionConfigurator.class)
Copy after login

在onOpen方法里加入参数 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);    }
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template