简体   繁体   中英

Use ContainerRequestFilter in Jersey without web.xml

I am trying to intercept requests in Jersey running inside Glassfish.

I created an implementation of ContainerRequestFilter

package mycustom.api.rest.security;

@Provider
public class SecurityProvider implements ContainerRequestFilter {
  @Override
  public ContainerRequest filter(ContainerRequest request) {
    return request;
  }
}

My app is started using a subclass of PackagesResourceConfig .

When Glassfish starts, Jerseys find my provider:

INFO: Provider classes found:
  class mycustom.rest.security.SecurityProvider

But it never hits that filter method. What am I missing??

Everything else seems to be working fine. I added a couple of ContextResolver providers to do JSON mapping and they work fine. Requests hit my resources fine, it just never goes through the filter.

I don't think container filters are loaded in as providers. I think you have to set the response filters property. Strangely PackagesResourceConfig doesn't have a setProperty() but you could overload getProperty() and getProperties() :

public Object getProperty(String propertyName) {
  if(propertyName.equals(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS)) {
    return new String[] {"mycustom.rest.security.SecurityProvider"};
  } else {
    return super.getProperty(propertyName);
  }
}

public Map<String,Object> getProperties() {
  propName = ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS;
  Map<String,Object> result = super.getProperties();
  result.put(propName,getProperty(propName));
  return result;
}

Actually, reading the javadocs more closely, it appears the preferred method is:

myConfig.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS,
                              new String [] {"mycustom.rest.security.SecurityProvider"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM