Undertow的路由模板格式
是否有关于undertow的路由模板格式的任何文档。我想这样设置处理程序:
/ or /index.html -> Use handler 1Anything else -> Use handler 2
我尝试了这个,但bu没用:
Handlers.routing() .add("GET", "/", handler1)
.add("GET", "/index.html", handler1)
.add("GET", "/*", handler2)
任何想法?
回答:
有两种方法可以实现此目的:
Handlers.path() .addExactPath("/path1", handler1)
.addPrefixPath("/path2", handler2);
将handler1只会匹配上 (或 )。
在handler2将匹配 , 和其他一切有开始 。
如果使用RoutingHandler,则可以选择轻松地从路径中提取变量。例如,这对于构建REST
API很方便(请注意上便捷get方法的用法RoutingHandler)。
Handlers.routing().get("/{test}/*", exchange -> { PathTemplateMatch pathMatch = exchange.getAttachment(PathTemplateMatch.ATTACHMENT_KEY);
String itemId1 = pathMatch.getParameters().get("test"); // or exchange.getQueryParameters().get("test")
String itemId2 = pathMatch.getParameters().get("*"); // or exchange.getQueryParameters().get("*")
}))
该*参数可以匹配任何东西(例如像路径a/b/c)。为了使用该*参数,您需要在路由模板中定义一个实际的命名参数(test在我的示例中)。
请注意,在路由模板中定义的参数将与查询参数(exchange.getQueryParameters())一起使用。这是默认行为。如果您不希望这样做,则可以像这样创建路由处理程序:Handlers.routing(false).get(...)然后从交换机的附件中检索参数。
对于您的路由处理程序不匹配的任何路由,您可以使用中的fallbackHandler可用路由RoutingHandler。
Handlers.routing() .get("/", handler1)
.get("/index.html", handler1)
.setFallbackHandler(handler2);
默认情况下,fallbackHandler简单地返回带有404状态代码的空响应正文。该handler2会匹配任何其他请求,不仅
请求。
您当然可以结合PathHandler并RoutingHandler满足您的需求。
这是一个更实际的设置的小示例:
Undertow.builder().addHttpListener(8080, "0.0.0.0") .setHandler(Handlers.path()
// REST API path
.addPrefixPath("/api", Handlers.routing()
.get("/customers", exchange -> {...})
.delete("/customers/{customerId}", exchange -> {...})
.setFallbackHandler(exchange -> {...}))
// Redirect root path to /static to serve the index.html by default
.addExactPath("/", Handlers.redirect("/static"))
// Serve all static files from a folder
.addPrefixPath("/static", new ResourceHandler(
new PathResourceManager(Paths.get("/path/to/www/"), 100))
.setWelcomeFiles("index.html"))
).build().start();
该应用程序还提供文件系统中的静态文件。例如,这很方便提供javascript应用程序或静态html文件。
以上是 Undertow的路由模板格式 的全部内容, 来源链接: utcz.com/qa/405655.html


