Riqk
Riqk

Reputation: 54

Adding a ContainerResponseFilter to jetty server

I want to add a ContainerResponseFilter and ContainerRequestFilter to my jetty-server. But when I try to add it, I get an error that the class is not good.

My jetty server-setup:

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addFilter(CorsFilter.class, //Error here
    "/*", EnumSet.of(DispatcherType.REQUEST));

Server jettyServer = new Server(8090);
jettyServer.setHandler(context);

ServletHolder jerseyServlet =
    context.addServlet(ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0); 
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
    Login.class.getCanonicalName());

Starter.start(jettyServer);

and my filter:

public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter  {

The error is that the method is not resolved. Thanks!

Upvotes: 1

Views: 761

Answers (1)

Joakim Erdfelt
Joakim Erdfelt

Reputation: 49515

ContainerRequestFilter and ContainerResponseFilter are not Servlet Filters, those are JAX-RS filters.

Register them with your ResourceConfig implementation.

Example:

@ApplicationPath("/")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        // Register resources and providers using package-scanning.
        packages("my.package");

        // Register my custom provider - not needed if it's in my.package.
        register(CorsFilter.class);
        // Register an instance of LoggingFilter.
        register(new LoggingFilter(LOGGER, true));

        ...
    }
}

Upvotes: 1

Related Questions