Jersey filters in non-servlet container

本小妞迷上赌 提交于 2019-12-12 05:53:23

问题


I am running Jersey in a non-servlet container (Netty). For servlet-based containers, I can plug in a request filter using :

<init-param>
         <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
         <param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>

But how do I do this programmatically in my case ?


回答1:


Here is a completely non-servlet example: Assuming you have created your request and/or response filter(s), you can add them to your startup code as follows: (Please note ApiInterceptor class is both a request and a response filter in this example)

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

    System.out.println("Investigating Api services...");        
    ResourceConfig rc = new PackagesResourceConfig(
        "path.to.your.resource.objects");

    System.out.println("Registering interceptors...");
    rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, ApiInterceptor.class.getName());
    rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, ApiInterceptor.class.getName());

    Debug.print("Starting grizzly...");
    GrizzlyServerFactory.createHttpServer(BASE_URI, rc);

    Debug.print("The app started @", BASE_URI.toString());
    Debug.print("Enjoy!");

    System.in.read();



回答2:


Not sure about Netty, but for Grizzly its:

    .....

    webServer = new GrizzlyWebServer(getPort(8080), ".", true);

    // add Jersey resource servlet

    ServletAdapter jerseyAdapter = new ServletAdapter();
    jerseyAdapter.addInitParameter("com.sun.jersey.config.property.packages", "com.your.resources.package");
    jerseyAdapter.setContextPath("/");
    jerseyAdapter.setServletInstance(new ServletContainer());

    // add the Container filter 
    jerseyAdapter.addInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, GZIPContentEncodingFilter.class.getName());


    webServer.addGrizzlyAdapter(jerseyAdapter, new String[]{"/"});


    try {
        // start Grizzly embedded server //
        System.out.println(String.format("Jersey app started with WADL at %sapplication.wadl", BASE_URI));
        webServer.start();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }


来源:https://stackoverflow.com/questions/6015999/jersey-filters-in-non-servlet-container

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