Search code examples
websocketsockjsspring-websocketservletcontextlistener

Unable to get ServletContext in Spring Controller when using Websockets


Client Code:
$scope.socket = new SockJS("ws/ws"); 
$scope.stompClient = Stomp.over($scope.socket); 
$scope.stompClient.connect("guest", "guest",connectCallback, errorCallback);

//in connectCallback
$scope.stompClient.subscribe('/topic/agent-sendstatus', showScreenPop);

Java Code:
    @MessageMapping("/agent-sendstatus")
        public void testmethod()
        {
            //How do i get ServletContext here to further implement solution?
            template.convertAndSend("/topic/agent-sendstatus","bcd");
        }

Please suggest. I am getting session using SimpMessageHeaderAccessor in the controller but i need ServletContext too. Is there some way in Spring?


Solution

  • When you upgrade to WebSocket there's no HTTP involved in the communication, the only place where you have HTTP is during the handshake. You could implement a HandshakeInterceptor to get the ServletContext and expose any parameter to the WebSocket session, so you can get them in your message handler method with a HeaderAccessor. Check out the HttpSessionHandshakeInterceptor for an example.