Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. How to specify path and get it?

like image 457
mystdeim Avatar asked Sep 26 '16 07:09

mystdeim


People also ask

How does undertow server work?

Undertow is a flexible performant web server written in java, providing both blocking and non-blocking API's based on NIO. Undertow has a composition based architecture that allows you to build a web server by combining small single purpose handlers.

What is io undertow?

Undertow is a Java web server based on non-blocking IO. It consists of a few different parts: A core HTTP server that supports both blocking and non-blocking IO. A Servlet 4.0/5.0 implementation.


1 Answers

You need a PathTemplateHandler and not a PathHandler, see:

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:

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. 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.

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

like image 127
ant1g Avatar answered Sep 19 '22 14:09

ant1g