ContainerRequestFilter ContainerResponseFilter doesn't get called

36,354

Solution 1

I added a Jersey Application class and registered the filter in the class, which solved my problem. Also upgraded my jersey version to 2.x from 1.x

public class MyApplication extends ResourceConfig {

    /**
     * Register JAX-RS application components.
     */
    public MyApplication () {
        register(RequestContextFilter.class);
        register(JacksonFeature.class);
        register(CustomerResource.class);
        register(Initializer.class);
        register(JerseyResource.class);
        register(SpringSingletonResource.class);
        register(SpringRequestResource.class);
        register(CustomExceptionMapper.class);
    }
}

Solution 2

I solved the problem on Wildfly 10 / rest easy like this (CORSFilter is my ContainerResponseFilter):

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> resources = new HashSet<Class<?>>();

        resources.add(CORSFilter.class);

        return resources;
    }
}

Solution 3

<init-param>
  <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
  <param-value>org.anchepedheplatform.infrastructure.core.filters.ResponseCorsFilter</param-value>
</init-param>

First, I wrote a class which implements com.sun.jersey.spi.container.ContainerResponseFilter

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

/**
* Filter that returns a response with headers that allows for Cross-Origin
* Requests (CORs) to be performed against the platform API.
*/
public class ResponseCorsFilter implements ContainerResponseFilter {

  @Override
  public ContainerResponse filter(final ContainerRequest request, final ContainerResponse   response) { 
      final ResponseBuilder resp = Response.fromResponse(response.getResponse());
      resp.header("Access-Control-Allow-Origin", "*")
      .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
      final String reqHead = request.getHeaderValue("Access-Control-Request-Headers");
      if (null != reqHead && !reqHead.equals(null)) {
      resp.header("Access-Control-Allow-Headers", reqHead);}
      response.setResponse(resp.build());
      return response;
 }

and later I had put this reference of this class in intit-param web.xml.

Share:
36,354
user2973475
Author by

user2973475

Updated on July 09, 2022

Comments

  • user2973475
    user2973475 almost 2 years

    I am trying to learn jersey by creating a small RESTful service. I want to use the Filters for specific reasons(Like I want to use the ContainerResponseFilter for CORS headers to allow cross domain requests). However, I am just not able to get these filters intercept my call. I have seen all the posts for this problem and most of them say to register with annotation provider or in web.xml. I have tried registering the files in web.xml as well as giving a @Provider annotation for the container

    Here is my web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- This web.xml file is not required when using Servlet 3.0 container, 
         see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html#d4e194 -->
    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/classes/spring/config/BeanLocations.xml</param-value>
        </context-param>
    
        <servlet>
            <servlet-name>Jersey Web Application</servlet-name>
            <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
                <param-name>com.sun.jersey.config.property.packages</param-name>
                <param-value>com.rest.example</param-value>
            </init-param>
            <init-param>  
                <param-name>jersey.config.server.provider.packages</param-name>  
                <param-value>com.rest.example.cors</param-value>
            </init-param>
            <init-param>
                <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
                <param-value>com.rest.example.CORSFilter</param-value>
            </init-param>
            <init-param>
                <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
                <param-value>com.rest.example.RequestFilter</param-value>
            </init-param>
    
        </servlet>
        <servlet-mapping>
            <servlet-name>Jersey Web Application</servlet-name>
            <url-pattern>/webresources/*</url-pattern>
        </servlet-mapping>
    
    </web-app>
    

    Here are my Filters:

    package com.rest.example.cors;
    
    import javax.ws.rs.ext.Provider;
    
    import com.sun.jersey.spi.container.ContainerRequest;
    import com.sun.jersey.spi.container.ContainerResponse;
    import com.sun.jersey.spi.container.ContainerResponseFilter;
    
    @Provider
    public class CORSFilter implements ContainerResponseFilter {
    
        public ContainerResponse filter(ContainerRequest creq,
                ContainerResponse cresp) {
    
                 cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
                 cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
                 cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
                 cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
    
                return cresp;
        }
    }
    
    
    package com.rest.example.cors;
    
    import javax.ws.rs.ext.Provider;
    
    import com.sun.jersey.spi.container.ContainerRequest;
    import com.sun.jersey.spi.container.ContainerRequestFilter;
    
    @Provider
    public class RequestFilter implements ContainerRequestFilter {
    
        public ContainerRequest filter(ContainerRequest request) {
            System.out.println("request filter");
            return request;
        }
    }
    

    Link to my github project.

    • Baldy
      Baldy almost 10 years
      What container/app server and version of Jersey are you using? Also, have you tried registering your filters in your Jersey Application class?
    • user2973475
      user2973475 almost 10 years
      Im using jersey version 1.8. Im using the VMware VFabric that comes with STS. How do we register the filters in jersey application class?
    • Baldy
      Baldy almost 10 years
      To register your filters, add them to the getClasses method in your javax.ws.rs.core.Application object although it appears your web.xml should be handling that for you. Are your REST methods are being called? How do you know your filters aren't being called?
    • user2973475
      user2973475 almost 10 years
      My REST methods are called. I set a debug point in my Filters and the code never hits the debug point, however it hits the resource methods.
    • Najeeb Arif
      Najeeb Arif over 7 years
      just add packages details which contain all the filters in your ResourceConfig. I have posted one exapmle also.
    • MrTesla
      MrTesla over 3 years
      ContainerResponseFilter's param-value is pointing to the wrong package/class.
  • Athafoud
    Athafoud about 9 years
    Is the code you provided taken from here CORS-Compliant REST API with Jersey and ContainerResponseFilter ?
  • Marcus Junius Brutus
    Marcus Junius Brutus over 7 years
    that worked for me in Jersey 2.24 deployed in Tomcat 8.5 but I also had to register the application class in web.xml as follows: <init-param><param-name>javax.ws.rs.Application</param-name>‌​<param-value>MyAppli‌​cation</param-value>‌​</init-param> (inside the servlet definition for org.glassfish.jersey.servlet.ServletContainer)
  • G-M
    G-M about 7 years
    Thanks this was my problem too.
  • Alexander Falk
    Alexander Falk almost 6 years
    Absolute wonderful! I totally forgot to add it to my ApplicationClass. Thank you a lot for that tip.