简体   繁体   English

简单的休息与下降

[英]Simple rest with undertow

I have this code for server: 我有这个代码服务器:

Undertow server = Undertow.builder()
        .addHttpListener(8080, "localhost")
        .setHandler(Handlers.path()
                .addPrefixPath("/item", new ItemHandler())
        )
        .build();
server.start();

And handler: 和处理程序:

private class ItemHandler implements HttpHandler {

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
        exchange.getPathParameters(); // always null
        //ItemModel item = new ItemModel(1);
        //exchange.getResponseSender().send(mapper.writeValueAsString(item));
    }
}

I want to send request /item/10 and get 10 in my parameter. 我想发送request /item/10并在我的参数中获得10。 How to specify path and get it? 如何指定路径并获取它?

You need a PathTemplateHandler and not a PathHandler , see: 您需要PathTemplateHandler而不是PathHandler ,请参阅:

Undertow server = Undertow.builder()
    .addHttpListener(8080, "0.0.0.0")
    .setHandler(Handlers.pathTemplate()
        .add("/item/{itemId}", new ItemHandler())
    )
    .build();
server.start();

Then, in your ItemHandler : 然后,在你的ItemHandler

class ItemHandler implements HttpHandler {

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
      exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");

      // Method 1
      PathTemplateMatch pathMatch = exchange.getAttachment(PathTemplateMatch.ATTACHMENT_KEY);
      String itemId1 = pathMatch.getParameters().get("itemId");

      // Method 2
      String itemId2 = exchange.getQueryParameters().get("itemId").getFirst();
    }
}

The method 2 works because Undertow merges parameters in the path with the query parameters by default. 方法2有效,因为Undertow默认情况下将路径中的参数与查询参数合并。 If you do not want this behavior, you can use instead: 如果您不想要此行为,则可以使用:

Handlers.pathTemplate(false)

The same applies to the RoutingHandler , this is probably what you want to use eventually to handle multiple paths. 这同样适用于RoutingHandler ,这可能是您最终要用于处理多个路径的内容。

Handlers.rounting() or Handlers.routing(false) Handlers.rounting()Handlers.routing(false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM