在WebsocketAdapter中获取ServletMapping [Jetty]

问题描述 投票:0回答:1

我需要Websocket-Connection的Path而不使用我的WebsocketAdapter中的前缀。

F.E. web.xml中给出的前缀是:

<servlet-mapping> 
    <url-pattern>
       /test/
    </url-pattern> 
</servlet-mapping>

现在我用Path打开一个Websocket

本地主机:8080 /测试/这此结果的路径-I-需要

将来我不想在更改url-pattern后更改我的Java-Server-Code。

我在WebSocketServlet中的configure-function调用的WebSocketCreator中创建了我的WebsocketAdapter。

根据我的研究,我认为我可以通过ServletMapping.getPathSpec()获得它。问题是我不知道如何获得ServletMapping。

任何想法如何解决这个问题? (不限于使用ServletMapping的可能解决方案)

java websocket embedded-jetty
1个回答
1
投票

注意:您的/test/的url-pattern永远不会匹配localhost:8080/test/this-is-the-path-i-need的URI,因为该URI不匹配。 如果你想让这个URI匹配,那么你将使用/test/*的url-pattern然后request.pathInfo将拥有你需要/想要的东西。

用于访问servlet / filter / websocket的WEB-INF/web.xml映射无法使用标准Servlet API从webapp中访问。

使用Servlet API捕获已使用的完整路径或URI,然后从中删除Servlet上下文路径前缀以获取所使用的路径。

为此,您将使用来自HttpServletRequest的标准Servlet ServletUpgradeRequest.getHttpServletRequest(),收集路径,删除上下文路径前缀,可选地收集pathInfo,然后将生成的路径传递到您刚创建的WebsocketAdapter中。

注意:ServletMapping是Jetty的内部类。它不是公共/正式的API,因此不鼓励使用它“将来我不想更改我的Java-Server-Code ...”的声明用例。

如果你仍然想要使用内部API,我建议完全跳过ServletMapping,只是为了这个特定的请求去使用PathSpec,你可以通过ServletUpgradeRequest属性访问它。

public static class MyPathSpecCreator implements WebSocketCreator
{
    private static final String PATHSPEC_KEY = PathSpec.class.getName();

    @Override
    public Object createWebSocket(ServletUpgradeRequest upgradeRequest,
                                  ServletUpgradeResponse upgradeResponse)
    {
        String pathSpecPattern = "/"; // default value (pick your own)
        PathSpec pathSpec = (PathSpec) upgradeRequest.getServletAttribute(PATHSPEC_KEY);
        if(pathSpec != null)
            pathSpecPattern = pathSpec.getDeclaration();
        return new MyWebSocketAdapter(pathSpecPattern);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.