websocket - 在 Embedded Jetty 9 上的带注释的 @WebSocket 类中访问 HttpSession

标签 websocket embedded-jetty jetty-9

如何访问 Jetty 9 中带注释的 @WebSocket 类中的 HttpSession 对象?

我找到了如何使用 @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 .

为方便起见,以下是我启动嵌入式 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();
    }

}

如果您需要更多信息,请与我们联系。

任何帮助将不胜感激。

提前致谢。

最佳答案

您将需要使用 WebSocketCreator 概念。

首先你设置WebSocketCreator您在 WebSocketServletFactory 中选择您在 WebSocketServlet 中配置的

public class MySessionSocketServlet extends WebSocketServlet
{
    @Override
    public void configure(WebSocketServletFactory factory)
    {
        factory.getPolicy().setIdleTimeout(30000);
        factory.setCreator(new MySessionSocketCreator());
    }
}

接下来,您需要获取 HttpSession在升级过程中并将其传递给您正在创建的 WebSocket 对象。

public class MySessionSocketCreator implements WebSocketCreator
{
    @Override
    public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp)
    {
        HttpSession httpSession = req.getSession();
        return new MySessionSocket(httpSession);
    }
}

最后,只需跟踪 HttpSession在你自己的WebSocket .

@WebSocket
public class MySessionSocket
{
    private HttpSession httpSession;
    private Session wsSession;

    public MySessionSocket(HttpSession httpSession)
    {
        this.httpSession = httpSession;
    }

    @OnWebSocketConnect
    public void onOpen(Session wsSession)
    {
        this.wsSession = wsSession;
    }
}

注意:HttpSession可以在 WebSocket 处于事件状态时过期并被清除和清理。此外,HttpSession此时的内容不能保证与其他 Web 操作的更改保持同步(这主要取决于您在服务器端使用的 Session 存储/缓存技术)

还有一个注意事项:抵制存储/跟踪 ServletUpgradeRequest 的冲动Socket 实例中的对象,因为该对象被 Jetty 适本地回收和清理。

关于websocket - 在 Embedded Jetty 9 上的带注释的 @WebSocket 类中访问 HttpSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27671162/

相关文章:

php - Websockets 不适用于 Google Chrome

scala - 使用自定义名称 Play WebSocketActor createHandler

java - Jetty RewriteHandler 和 RewriteRegexRule

ssl - Jetty 9 无法使用 OpenSSL 生成的自签名证书

java - 如何在 Jetty-9 上使用证书执行自定义客户端身份验证?

amazon-web-services - 在 AWS Elastic Beanstalk 上使用 Tomcat 7 的 Websocket

scala - scala/akka/play中的简单Websocket

java - Jetty 9 + Spring Boot - 由于缺少 ServletWebServerFactory bean,无法启动 ServletWebServerApplicationContext

servlets - 嵌入式 Jetty 8.0 中的 Servlet 3.0 支持