我有这个服务器的代码:
Undertow server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(Handlers.path()
.addPrefixPath("/item", new ItemHandler())
)
.build();
server.start();
和处理程序:
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));
}
}
我想发送请求/item/10
并在我的参数中获得10。如何指定路径并获取它?
答案 0 :(得分:6)
您需要celsius
而不是PathTemplateHandler
,请参阅:
PathHandler
然后,在Undertow server = Undertow.builder()
.addHttpListener(8080, "0.0.0.0")
.setHandler(Handlers.pathTemplate()
.add("/item/{itemId}", new ItemHandler())
)
.build();
server.start();
:
ItemHandler
方法2有效,因为Undertow默认情况下将路径中的参数与查询参数合并。 如果您不想要此行为,则可以改为使用:
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();
}
}
同样适用于Handlers.pathTemplate(false)
,这可能是您最终要用来处理多个路径的内容。
RoutingHandler
或Handlers.rounting()