如何在Jetty 9中的帶註釋的@WebSocket類中訪問HttpSession對象?在Embedded Jetty 9中註解的@WebSocket類中訪問HttpSession 9
我發現瞭如何使用它@ServerEndpoint註釋,就像在這裏做:在類波紋管HttpSession from @ServerEndpoint
使用@WebSocket註解一樣,我該怎麼辦呢?
@WebSocket
public class AuctionWebSocket {
// NEED TO ACCESS HttpSession OBJECT INSIDE THESE METHODS:
@OnWebSocketConnect
public void onConnect(Session session) {
System.out.println("onConnect...");
}
@OnWebSocketMessage
public void onMessage(String message) {
System.out.println("Message: " + message);
}
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("onClose...");
}
@OnWebSocketError
public void onError(Throwable t) {
System.out.println("onError...");
}
}
裏面的方法onConnect(Session session)
,席力圖召session.getUpgradeRequest().getSession()
它總是返回null
。
有關的信息的緣故,這裏是我開始嵌入碼頭9:
public class Main {
public static void main(String[] args) throws Exception {
String webPort = System.getenv("PORT");
if (webPort == null || webPort.isEmpty()) {
webPort = "8080";
}
Server server = new Server(Integer.parseInt(webPort));
ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
classlist.addBefore("org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
"org.eclipse.jetty.annotations.AnnotationConfiguration");
WebAppContext wac = new WebAppContext();
String webappDirLocation = "./src/main/webapp/";
wac.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/classes/.*");
wac.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
wac.setBaseResource(new ResourceCollection(new String[]{webappDirLocation, "./target"}));
wac.setResourceAlias("/WEB-INF/classes/", "/classes/");
wac.setContextPath("/");
wac.setParentLoaderPriority(true);
/*
* WebSocket handler.
*/
WebSocketHandler wsh = new WebSocketHandler() {
@Override
public void configure(WebSocketServletFactory wssf) {
wssf.register(AuctionWebSocket.class);
}
};
ContextHandler wsc = new ContextHandler();
wsc.setContextPath("/auction-notifications");
wsc.setHandler(wsh);
ContextHandlerCollection chc = new ContextHandlerCollection();
chc.setHandlers(new Handler[]{wac, wsc});
server.setHandler(chc);
server.start();
server.join();
}
}
讓我知道如果你需要更多的信息。
任何幫助將不勝感激。
在此先感謝。
我只想訪問「HttpSession」中記錄的用戶以維護用戶及其相應websocket會話的地圖以進一步通信。作爲一種解決方法,在'onopen' javascript回調函數中,我使用用戶標識向WebSocket發送消息,如下所示:ws.onopen = function(){ws.send(「onopen:」+ sessionId_); };' 然後,我在服務器上進行用戶和websocket會話之間的關聯。 您認爲這種方法比通過WebSocketCreator概念訪問'HttpSession'好嗎? – reinaldoluckman 2014-12-29 23:40:31
我有類似的要求,(我的要求是,如果同一用戶在多個選項卡中打開應用程序,則會創建多個websocket會話,因此如果用戶在一個選項卡中註銷,我想從所有選項卡註銷用戶),請問您可以幫助你如何解決問題? – Jayesh 2017-02-26 04:53:12
@Jayesh請爲新主題打開一個新問題 – 2017-02-27 14:08:25