2016-09-28 29 views
3

是否有關於流水線路由模板格式的任何文檔。我想設置的處理程序是這樣的:流水線路由模板格式

/ or /index.html -> Use handler 1 
Anything else -> Use handler 2 

我想這一個,BU沒有工作:

Handlers.routing() 
     .add("GET", "/", handler1) 
     .add("GET", "/index.html", handler1) 
     .add("GET", "/*", handler2) 

任何想法?

回答

11

有一對夫婦的方式來實現這一目標:

1)基本方法:PathHandler

Handlers.path() 
    .addExactPath("/path1", handler1) 
    .addPrefixPath("/path2", handler2); 

handler1將只匹配在/PATH1(或/路徑1/ )。

handler2將匹配/路徑/路徑/和其他一切與/路徑/開始。

2)路線方針:RoutingHandler

如果使用RoutingHandler,你可以選擇容易從路徑中提取的變量。例如,這對於構建REST API很方便(請注意RoutingHandler上方便的get方法的使用)。

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(...)然後從交換機的附件中檢索參數。

對於任何與您的路由處理程序不匹配的路由,可以使用RoutingHandler中的fallbackHandler

Handlers.routing() 
     .get("/", handler1) 
     .get("/index.html", handler1) 
     .setFallbackHandler(handler2); 

默認情況下,簡單地fallbackHandler返回一個空應答體404個狀態碼。 handler2將匹配任何其他請求,不僅GET請求。

綜合實例

你當然也可以結合PathHandlerRoutingHandler,以滿足您的需求。

這裏是一個更現實的設置的一個小例子:

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文件提供服務。

+0

謝謝你的回答。你的回答對我的例子是正確的,但我的意思是處理通配符的一般方法。如果我們有兩個'/ sample1/*'和'/ sample2/*',那麼單個回退處理程序不起作用。 – user1079877

+0

我編輯了我的答案 – aramaki

+0

謝謝,它的工作原理! – user1079877