Using Jersey with Grizzly

≡放荡痞女 提交于 2019-12-11 05:31:47

问题


I want to create a simple REST service, and for that I am using Jersey and Grizzly.

Here is my Service class:

@Path("/service")
class TestRESTService {

    @GET
    @Path("test")
    @Produces(Array(MediaType.APPLICATION_JSON))
    public String test() {
        return "{ \"TestField\" : \"TestValue\" }";
    }

}

And from what I understand here is how I supposed to start it:

ResourceConfig config = new ResourceConfig();
config.registerClasses(TestRESTService.class);
URI serverUri = UriBuilder.fromUri("http://localhost/").port(19748).build();
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(serverUri, config);
server.start();

But it's not working. :( I tried to send a request to

http://localhost:19748/service/test

using Google Chrome's Postman plugin by adding 'Accept' : 'application/json' as a Http Header, but nothing is returned. The 'hourglass' is just spinning around.

Could you please help me?


回答1:


This one works for me:

private static String API_PACKAGE = "package where TestRESTService class";

public static final URI BASE_URI = UriBuilder
        .fromUri("http://localhost/")
        .port(8000)
        .build();

private static HttpServer initServer() throws IOException {
    System.out.println("Starting grizzly... " + BASE_URI);

    HttpServer httpServer = GrizzlyServerFactory.createHttpServer(BASE_URI, new HttpHandler() {
        @Override
        public void service(Request rqst, Response rspns) throws Exception {
            rspns.sendError(404);
        }
    });

    // Initialize and register Jersey Servlet
    WebappContext context = new WebappContext("GrizzlyContext", "/");
    ServletRegistration registration = context.addServlet(
            ServletContainer.class.getName(), ServletContainer.class);
    registration.setInitParameter(ServletContainer.RESOURCE_CONFIG_CLASS,
            PackagesResourceConfig.class.getName());
    registration.setInitParameter(PackagesResourceConfig.PROPERTY_PACKAGES, API_PACKAGE);
    registration.addMapping("/*");
    context.deploy(httpServer);

    return httpServer;
}   


来源:https://stackoverflow.com/questions/22593983/using-jersey-with-grizzly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!