繁体   English   中英

与Grizzly一起使用Jersey

[英]Using Jersey with Grizzly

我想创建一个简单的REST服务,为此,我正在使用Jersey和Grizzly。

这是我的服务班级:

@Path("/service")
class TestRESTService {

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

}

从我的理解中,我应该如何开始:

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();

但这不起作用。 :(我试图向发送请求

http://localhost:19748/service/test

使用Google Chrome的Postman插件,方法是将'Accept':'application / json'添加为Http标头,但不会返回任何内容。 “沙漏”正在旋转。

请你帮助我好吗?

这对我有用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM