I have an endpoint with:
@POST
@Path("/test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String canaryTest(String JSON) {
return JSON;
}
When I register it in Jetty using Jersey
ServletHolder holder = new ServletHolder(new ServletContainer());
everything seems to work fine. But in case I try to specify explictly the default config, it stops working (returning a media type error from the endpoint). Even by just passing a default instance of a ResourceConfig to the ServletContainer, it stops working.
ResourceConfig config = new ResourceConfig();
//config.property(x,defaultX)
//config.property(y,defaultY)
ServletHolder holder = new ServletHolder(new ServletContainer(config));
I'd like to emulate the default configuration behavior manually and explicitly, so what I am asking here is how should I configure ResourceConfig so the behavior keeps working (i.e, what properties to set)
P.S: i'm using Jetty 9.2.6.v20141205 and Jersey 2.14. Dependencies in Maven:
I don't know how you got this to work
ServletHolder holder = new ServletHolder(new ServletContainer());
I could not produce a working example simply instantiating the ServletContainer()
. Though I was about to get it to work with the following code
public class TestJerseyServer {
public static void main(String[] args) throws Exception {
ResourceConfig config = new ResourceConfig();
config.packages("jetty.practice.resources");
ServletHolder jerseyServlet
= new ServletHolder(new ServletContainer(config));
Server server = new Server(8080);
ServletContextHandler context
= new ServletContextHandler(server, "/");
context.addServlet(jerseyServlet, "/*");
server.start();
server.join();
}
}
Using all your dependencies, excluding the com.sun.jersey:jersey-json
, as it's not needed. No other configuration. The resource class
@Path("test")
public class TestResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getTest() {
Hello hello = new Hello();
hello.hello = "world";
return Response.ok(hello).build();
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response postHello(Hello hello) {
return Response.ok(hello.hello).build();
}
public static class Hello {
public String hello;
}
}
in the jetty.practice.resources
package.
I'm curious to see how you got it to work without the ResourceConfig
Another thing I should mention is that jersey-container-servlet-core
should be switched out for jersey-container-servlet
. The former is for 2.5 container support, but the latter is recommended for 3.x containers. It not have any effect though, with my example
cURL
C:\>curl http://localhost:8080/test -X POST -d "{\"hello\":\"world\"}" -H "Content-Type:application/json"
world
C:\>curl http://localhost:8080/test
{"hello":"world"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With