Accessing ServletContext and HttpSession in @OnMessage of a JSR-356 @ServerEndpoint

前端 未结 4 2173
小鲜肉
小鲜肉 2020-12-05 04:29

I need to get the ServletContext from inside a @ServerEndpoint in order to find Spring ApplicationContext and lookup for a Bean.

4条回答
  •  Happy的楠姐
    2020-12-05 05:11

    Updated code for BalusC's answer, the onOpen method needs to be decorated with @OnOpen. Then there is no need anymore to extend the Endpoint class:

    @ServerEndpoint(value="/your_socket", configurator=ServletAwareConfig.class)
    public class YourSocket {
    
        private EndpointConfig config;
    
        @OnOpen
        public void onOpen(Session websocketSession, EndpointConfig config) {
            this.config = config;
        }
    
        @OnMessage
        public void onMessage(String message) {
            HttpSession httpSession = (HttpSession) config.getUserProperties().get("httpSession");
            ServletContext servletContext = httpSession.getServletContext();
            // ...
        }
    
    }
    

提交回复
热议问题