2

I'd like to add a Access-Control-Allow-Origin header to all Jersey requests in my application. Is it possible to do this via the Jersey servlet so it's application wide?

ServletRegistration jerseyServletRegistration =
      ctx.addServlet("JerseyServlet", new ServletContainer());
jerseyServletRegistration.setInitParameter(
      "com.sun.jersey.config.property.packages", "com.production.resource");
jerseyServletRegistration.setInitParameter(
      "com.sun.jersey.api.json.POJOMappingFeature", "true");
jerseyServletRegistration.setLoadOnStartup(1);
jerseyServletRegistration.addMapping("/api/*");
4

2 回答 2

0
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.filter.ClientFilter;

public final class JerseySample {

  public static void main(final String[] args) {
    final Client client = Client.create();

    client.addFilter(new ClientFilter() {

      @Override
      public ClientResponse handle(final ClientRequest request) {
        final Map<String, List<Object>> headers = request.getHeaders();

        final List<Object> valueList = new ArrayList<Object>();

        valueList.add("Sample Value");

        headers.put("Sample-Header", valueList);

        return getNext().handle(request);
      }

    });

    ...
  }

}

http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/api/client/filter/ClientFilter.html

于 2013-08-27T07:33:40.177 回答
0

Jersey 2.9.9 (2019) 使用标准 JAX-RS API:

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.WebTarget;

    ClientRequestFilter tokenHeadersAdder = new ClientRequestFilter()
    {
        public void filter(ClientRequestContext ctx) throws IOException
        {
            final Map<String, List<Object>> headers = ctx.getHeaders();
            headers.put("X-MyKey1", Collections.singletonList("MyValue1"));
        }
    };

    Client client = ClientBuilder.newClient(clientConfig);
    client.register(tokenHeadersAdder);
    WebTarget webTarget = client.target("http://...").build();

我建议只使用一个过滤器实例并使其成为线程安全的。

Javadoc中有一条注释:

实现此接口的过滤器必须使用 @Provider 注释

这似乎不是真的。

于 2019-06-10T02:11:23.810 回答