users@jersey.java.net

[Jersey] Re: Jersey2 Apply filter to requests only?

From: Miroslav Fuksa <miroslav.fuksa_at_oracle.com>
Date: Fri, 02 Aug 2013 11:51:38 +0200

Hi,

you can bind the existing jersey filter to only ContainerRequestFilter
contract. If you use the ResourceConfig to build the application,
register this binder:

org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.filter.LoggingFilter;
import javax.ws.rs.container.ContainerRequestFilter;

         ...
         resourceConfig.register(new AbstractBinder() {
             @Override
             protected void configure() {
bind(LoggingFilter.class).to(ContainerRequestFilter.class);
             }
         });

In this case, you must not register the filter as a standard provider
but only in this way.

You can write your own Feature that registers this binder into the
Configurable if you don't construct your application programmatically
using ResourceConfig.

Mira


On 08/02/2013 11:42 AM, algermissen1971 wrote:
> On 02.08.2013, at 11:25, Piers Powlesland <piers_at_aptusinteractive.com> wrote:
>
>> Hi I'm trying to log requests as they come into the web application I am writing. I cannot see how to do this I have managed to log both requests and responses by calling "register(new LoggingFilter())" in my resource configuration class, but it is not clear to me how I can apply a filter to requests only?
> Did you write LoggingFilter yourself?
>
> You should implement a filter that only extends ContainerRequestFilter, not also ContainerResponseFilter.
>
> Jan
>
> E.g:
>
>
>
> package xxxx;
>
> import java.io.IOException;
> import java.io.OutputStream;
> import java.util.List;
> import java.util.logging.Level;
> import java.util.logging.Logger;
>
> import javax.ws.rs.container.ContainerRequestContext;
> import javax.ws.rs.container.ContainerRequestFilter;
> import javax.ws.rs.container.ContainerResponseContext;
> import javax.ws.rs.container.ContainerResponseFilter;
> import javax.ws.rs.core.MultivaluedMap;
>
> public class ContainerLoggingFilter implements ContainerRequestFilter {
>
> private static Logger log = Logger.getLogger(ContainerLoggingFilter.class.getName());
> private String name;
>
> public ContainerLoggingFilter(String name) {
> this.name = name;
> }
>
> @Override
> public void filter(ContainerRequestContext req) throws IOException {
> log.log(Level.INFO,
> name + "REQ START ------------------------------");
> log.log(Level.INFO, name + "> " + req.getMethod() + " ");
> MultivaluedMap<String, String> headers = req.getHeaders();
> for (String key : headers.keySet()) {
> List<String> values = headers.get(key);
> log.log(Level.INFO, name + "> " + key + ": " + values);
> }
> log.log(Level.INFO,
> name + "REQ END ------------------------------");
>
> }
>
>
> }
>
>
>
>> Anyone have an idea?
>>
>> Thanks
>>
>> Piers