Solution to get httpsession in spring webSocket

Keywords: Session Spring JSON

If you don't know the basic usage of spring webSocket, please refer to: webSocket implementation of code scanning login

Handshake Interceptor: the implementation class of HttpSessionHandshakeInterceptor overrides the beforeHandshake method, as follows

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
			Map<String, Object> attributes) throws Exception {
		System.out.println("Before Handshake");
//		if (request instanceof HttpServletRequest) {
//			String currHttpSessionId = ((HttpServletRequest)request).getSession().getId();
//			logger.debug("currHttpSessionId:{}", currHttpSessionId);
//			attributes.put("currHttpSessionId", currHttpSessionId);
//		}else{
//			logger.warn("request is not HttpServletRequest"); / / execution result is not HttpServletRequest
//		}
		//Get httpsession
		 if (request instanceof ServletServerHttpRequest) {  
	            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;  
	            HttpSession httpSession = servletRequest.getServletRequest().getSession(false);  
	            if (httpSession != null) {  
	            	logger.debug("HttpSessionId:"+httpSession.getId());
	                attributes.put("currHttpSession",httpSession);  
	            }else{  
	                logger.debug("httpsession is null");  
	            }  
	        }  
		return super.beforeHandshake(request, response, wsHandler, attributes);
	}

As shown in the above code, get the httpsession object and save it in attributes. After that, each method in the message processing class can get the current socketsession. Through this socketSession.getAttributes(); get the map to get the httpsession object associated with the current long connection. As follows:

Message processing class: Methods in the implementation of TextWebSocketHandler can use methods like the following to get httpsession objects

// When the connection is ready
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.debug("[{} : {}] has be connected...", session.getUri(), session.getId());
		// Get httpsession
		Map<String, Object> attributes = session.getAttributes();
		System.out.println("attributesMap:" + attributes.toString());
		HttpSession httpSession = (HttpSession) attributes.get("currHttpSession");
		System.out.println("httpSessionId:" + httpSession.getId());
		SESSION_MAP.put(session.getId(), session);
		// Send sessionId to the front end
		logger.info("Return id");
		Msg4Ws<String> msg4Ws = new Msg4Ws<String>(10000, "ws Of sessionId", session.getId());
		String message = new ObjectMapper().writeValueAsString(msg4Ws); // Turn to json
		TextMessage returnMessage = new TextMessage(message);
		session.sendMessage(returnMessage);
	}

The printing results are as follows:

It is found in the screenshot that the attributes will contain a string with the key of HTTP.SESSION.ID by default, which is exactly the Id of httpsession. If the httpsession listener of the project saves all httpsessions, you can use this httpsessionId to get the httpsession.

Posted by ejaboneta on Wed, 01 Apr 2020 16:45:10 -0700