Tomcat中通过JavaEE实现的WebSocket程序获取ServletContext

在JavaEE7的WebSocket程序与Tomcat环境中,WebSocket session与HTTP session不互通。为了解决WebSocket上下文获取HTTP上下文中的用户信息问题,可以采取在HTTP session创建时建立WebSocket Endpoint,并通过ServerEndPointConfig的userProperties注入HttpSession。在WebSocket的onOpen、onMessage等回调中,可以从userProperties获取context对象,实现数据共享。以下是具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在通过WebSocket(在本文中WebSocket实现使用JavaEE7中的实现)构建的web程序中,默认的WebSocket的session和http请求的session是不能互通的。也就是说WebSocket的上下文环境和http的上下文环境是相互隔离的,比如,在一个web系统中,用户登录是通过http请求发起的,用户的信息都是存储在http的上下文环境中,而在用户登录之后,需要查看的报表数据是通过websocket协议进行通信的,那么此时如果想要在websocket的上下文环境中获取之前缓存在http请求中的用户信息,就无法获取。

针对该问题,我的解决办法是

1.在http的session创建时,再创建WebSocket的EndPoint

2.在该EndPoint创建过程中,将httpsession对象通过ServerEndPointConfig的userProperties对象进行注入

3.在WebSocket的EndPoint的各个回调方法(onOpen,onMessage等)中通过userProperties获取注入的context或session对象

该解决办法同样适用于WebSocket需要与http context进行数据共享的情况。

以下的代码展示对context对象进行共享

在context 监听器中添加WebSocket端点的代码

@WebListener
public class SystemInitListener implements ServletContextListener {

	private final static Logger logger = Logger
			.getLogger(SystemInitListener.class);

	/**
	 * Default constructor.
	 */
	public SystemInitListener() {
	}

	/**
	 * 系统初始化
	 */
	public void contextInitialized(ServletContextEvent ctxEvent) {
		logger.info("System init");

		//
                addEndpoints(ctxEvent);
                logger.info("System init end");
	}

	/**
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.info("SIL destoried");
	}
	
	/**
	 * 添加ws端点
	 * @param ctxEvent
	 */
	private void addEndpoints(ServletContextEvent ctxEvent) {
		/*********Endpoint *******************/
		final ServerContainer serverContainer = (ServerContainer)ctxEvent
				.getServletContext().getAttribute(
						"javax.websocket.server.ServerContainer");
		try {
			ServerEndpointConfig c = ServerEndpointConfig.Builder.create(
					PageEndpoint.class, "/page").build();
			c.getUserProperties().put("ServletContext",
					ctxEvent.getServletContext());
			
			serverContainer.addEndpoint(c);
		} catch (DeploymentException e) {
			logger.error(e.getMessage());
			logger.error(CommonUtils.getStackTraceAsString(e));
		}
	}
}

在WebSocket中获取该context对象

servletContext = (ServletContext)session.getUserProperties().get("ServletContext");
servletContext.getAttribute("users");

通过以上的代码片段可以实现WebSocket环境与Tomcat中Http环境的互通。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值