ContainerRequestFilter ContainerResponseFilter不会被调用

时间:2014-05-15 06:35:15

标签: rest servlets jersey jax-rs httpresponse

我正在尝试通过创建一个小型RESTful服务来学习球衣。我想出于特定原因使用过滤器(就像我想使用 ContainerResponseFilter 用于 CORS 标头来允许跨域请求)。但是,我只是无法让这些过滤器拦截我的电话。我已经看到了这个问题的所有帖子,他们中的大多数都说要注册注释提供者或web.xml。 我尝试在 web.xml 中注册文件,并为容器提供@Provider注释

这是我的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>

以下是我的过滤器:

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到我的github项目。

4 个答案:

答案 0 :(得分:10)

我添加了一个Jersey Application类并在类中注册了过滤器,这解决了我的问题。还将我的球衣版本从1.x升级到2.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);
    }
}

答案 1 :(得分:6)

我解决了Wildfly 10 / rest这样的问题(CORSFilter是我的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;
    }
}

答案 2 :(得分:1)

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

首先,我写了一个实现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;
 }

后来我把这个类的引用放在 intit-param web.xml中。

答案 3 :(得分:0)

如果您要扩展ResourceConfig课程,注册所有提供者的过程可能会很乏味,而且很可能会错过很少的提供者。

使用ResourceConfig类型可以执行的操作是,您可以在默认构造函数中使用packages方法来指定包含其余资源和提供程序的packages("")。对于Instance,我们假设我们有一个包com.test.poc.rest,其中包含所有其他服务,另一个包com.test.poc.providers,那么我们的resourceConig将如下所示:

public class CustomResourceConfig extends ResourceConfig{
    public CustomResourceConfig(){
       super();
       packages("com.test.poc.rest;com.test.poc.providers");
       //register any custom features
       register(JacksonFeature.class);         // enabling JSON feature.
    }
}

and boom jersey现在将扫描您使用@Path注释的网络服务以及使用@Provider注释的提供商。