【问题标题】:Jetty: How to nest HandlerWrapper, HandlerList, and ContextHandlerCollection, and ContextHandlerJetty:如何嵌套HandlerWrapper、HandlerList、ContextHandlerCollection、ContextHandler
【发布时间】:2017-01-03 17:00:39
【问题描述】:

我正在尝试在 Jetty 上构建一个 api 服务器。

我希望在类似于 /apis/api1/endpoint、/apis/api2/endpoint、/apis/api3/endpoint 等的路由上拥有多个 api

本质上,我有一个 HandlerWrapper,它包含一个 ContextHandlerCollections 的 HandlerList,本质上就是这样:

public void handle(...) {
    if (uri.startsWith("/apis/")) {
        log.info("This is an api request");
        this.getHandlerList.handle(...)
    } else {
        super.handle()
    }
}

private HandlerList getHandlerList() {
    HandlerList handlerList = new HandlerList();
    ContextHandlerCollection contextHandlerCollection = new ContextHandlerCollection();
    ContextHandler api1 = new ContextHandler("/apis/api1/endpoint");
    api1.setHandler(new Api1Handler());
    contextHandlerCollection.addHandler(api1);
    handlerList.addHandler(contextHandlerCollection);
    return handlerList
}

现在当我尝试这样做时:

curl localhost:port/apis/api1/endpoint

我收到 404 未找到,但我在日志中看到“这是一个 api 请求”语句。

有什么提示吗?

我基本上希望每个 api1、api2 等都有一个 ContextHandlerCollection。ContextHandlerCollection 应该由一组特定于端点的处理程序组成以供选择。

我错过了什么?

干杯,

【问题讨论】:

    标签: java jetty embedded-jetty


    【解决方案1】:

    Handler - 处理请求的基本形式,它不是请求处理的终点,除非您调用request.setHandled(true)

    HandlerWrapper - 一个处理程序,它可以执行一些处理并决定是否应将请求交给嵌套(包装)处理程序。

    HandlerCollection - 处理程序集合,遵循有关执行顺序的标准 java 集合规则。集合中的每个处理程序都会执行,直到其中一个调用request.setHandled(true)

    HandlerList - 一个专门的 HandlerCollection,它遵循 java.util.List 子处理程序的执行顺序

    ContextHandler - 一个专门的 HandlerWrapper,只有在请求上下文路径和虚拟主机匹配时才执行其包装的 Handler。

    ContextHandlerCollection - ContextHandler 的 HashMap,只会执行那些与请求上下文路径(和虚拟主机)匹配的子处理程序(在集合中)

    【讨论】:

    • 这当然是正确的方向。我最终只是想出了自己的处理程序,因为这比查找文档更容易:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 2017-01-10
    相关资源
    最近更新 更多