I would like to handle a variety of HTTP methods on the same URL. i.e
GET http://localhost:8081/test
POST http://localhost:8081/test
I was originally thinking I could create a separate HTTPHandler for each method, but what I'm not clear on is how to route the request to the correct handler. Is there some filter higher up that I'm missing? I'm currently adding multiple HTTPHandlers to the server configuration, but only the first handler is being called.
Or do I have the wrong idea? Should I be using a single HTTPHandler for all requests to the same path and just check the HTTP method and respond accordingly?
import java.net.URI;
import javax.ws.rs.client.ClientBuilder;
import org.glassfish.grizzly.http.Method;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
public class HttpHandlerTest
{
private static final URI BASE_URI = URI.create("http://localhost:8081");
private static final String MAPPING = "/test";
public static void main(String[] args)
{
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, (GrizzlyHttpContainer) null, false, null, true);
server.getServerConfiguration().addHttpHandler(new GetHandler(), MAPPING);
server.getServerConfiguration().addHttpHandler(new PostHandler(), MAPPING);
javax.ws.rs.core.Response getResponse = ClientBuilder.newClient().target(BASE_URI + MAPPING).request().get();
System.out.println(getResponse.readEntity(String.class));
javax.ws.rs.core.Response postResponse = ClientBuilder.newClient().target(BASE_URI + MAPPING).request().post(null);
System.out.println(postResponse.readEntity(String.class));
server.shutdown();
}
public static class GetHandler extends HttpHandler{
@Override
public void service(Request request, Response response) throws Exception{
if (request.getMethod() == Method.GET){
// handle GET only, move on if method is something else
response.getWriter().write("GET response");
}
else
{
// let another HTTPHandler handle this
response.getWriter().write("I wanted a different handler to handle this");
}
}
}
public static class PostHandler extends HttpHandler{
@Override
public void service(Request request, Response response) throws Exception{
if (request.getMethod() == Method.POST){
// handle GET only, move on if method is something else
response.getWriter().write("POST response");
}
}
}
}