如何访问 Jetty 9 中带注释的 @WebSocket 类中的 HttpSession 对象?
我找到了如何使用 @ServerEndpoint 注释来做到这一点,就像这里:来自 @ServerEndpoint 的 HttpSession
使用@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()
which 总是返回null
。
为方便起见,以下是我启动嵌入式 Jetty 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();
}
}
如果您需要更多信息,请与我们联系。
任何帮助将不胜感激。
提前致谢。