与Grizzly一起使用Jersey [英] Using Jersey with Grizzly

查看:127
本文介绍了与Grizzly一起使用Jersey的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的服务班级:

@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

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

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.

能请你帮我吗?

推荐答案

这个对我有用:

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

这篇关于与Grizzly一起使用Jersey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆