1. 程式人生 > >websocket @ServerEndpoint註解形式開發 @OnOpen 如何獲取httpSession

websocket @ServerEndpoint註解形式開發 @OnOpen 如何獲取httpSession

通過Configurator獲取httpsession,通過httpsession可獲取service 

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;

public class GetHttpSessionConfigurator extends Configurator{
    @Override  
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {  
        HttpSession httpSession = (HttpSession) request.getHttpSession();  
        if(httpSession != null){  
            config.getUserProperties().put(HttpSession.class.getName(), httpSession);  
        }  
    }  
}
第二步編寫@ServerEndpoint,並在onOpen 方法中獲取service

@ServerEndpoint(value = "/websocket/chat",configurator=GetHttpSessionConfigurator.class)
public class MyWebSocket{ 

//  private static final Log log = LogFactory.getLog(ChatAnnotation.class);  
//  private WebSocketService webSocketService;
    //靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。  
    private final static AtomicInteger onlineCount = new AtomicInteger(0);  
    //concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。若要實現服務端與單一客戶端通訊的話,可以使用Map來存放,其中Key可以為使用者標識  
//  private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>(); 
    private static List<MyWebSocket> clients = new ArrayList<>();
    //與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
    private Session session;  
    private HttpSession httpSession;
//  ngs static int userid ; 

    @OnOpen  
    public void onOpen(Session session, EndpointConfig config) throws IOException, InterruptedException  {  
        System.out.println("Open!");
        this.session = session;  
        this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());  
        if(httpSession != null){  
            ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(httpSession.getServletContext());  
            SharedFarmUsersManager sharedFarmUsersManager = (SharedFarmUsersManager) ctx.getBean("sfum"); 
            List<?> list = sharedFarmUsersManager.selectListBySql("select name from f_yh where id=1", null);
            System.out.println(list);
        }  
        clients.add(this);  //當前客戶端加入集合
//      addOnlineCount();   //線上數加1,對應的建立一個上鎖的方法
        MyWebSocket.onlineCount.incrementAndGet();//線上數加1
//      String message = "登入成功";
//      broadcast(message); 
        sendLatestNews();
    }  

第三步,由於HTTP協議與websocket協議的不同,導致沒法直接從websocket中獲取協議,放出去執行,會報空指標值異常,因為這個HttpSession並沒有設定進去。而設定HttpSession。需要寫一個繼承ServletRequestListener的監聽器。

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
@WebListener//配置Listener
@Component
public class RequestListener implements ServletRequestListener {

    public void requestInitialized(ServletRequestEvent sre)  {
        //將所有request請求都攜帶上httpSession
        ((HttpServletRequest) sre.getServletRequest()).getSession();

    }
    public RequestListener() {
    }

    public void requestDestroyed(ServletRequestEvent arg0)  {
    }
}