2016-09-26 89 views
4

我有服務器驗證碼:簡單的REST與暗流

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

和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)); 
    } 
} 

我想在我的參數發送請求/item/10並獲得10。如何指定路徑並獲取它?

回答

2

你需要一個PathTemplateHandler而不是PathHandler,請參閱:

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

然後,在你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(); 
    } 
} 

方法2家中使用,因爲暗潮合併參數路徑與查詢參數默認。 如果不希望這種行爲,你可以改用:

Handlers.pathTemplate(false)

這同樣適用於RoutingHandler,這可能是你要使用最終處理的多條路徑是什麼。

Handlers.rounting()Handlers.routing(false)

+0

安特例如對於post數據? –