0

I have implemented a filter as below -

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;

@WebFilter("/login.jsf")
public class ServiceFilter implements ContainerRequestFilter, ContainerResponseFilter, Filter {

public ServiceFilter() {}

@PostConstruct
public void init() {
    logger.debug("initialized.");
}
@Override
public void destroy() {
    logger.debug("destroyed");
}

@Override
public void init(FilterConfig arg0) throws ServletException {
//nothing here
}
...other method overides
}

When I deploy it on Wildfly10, I see the below gets printed

TIMESTAMP DEBUG ServiceFilter:65 - Initialized (ServiceFilter@39df1f0b)
TIMESTAMP DEBUG ServiceFilter:65 - Initialized (ServiceFilter@1a33dd9)

ServiceFilter class is also registered as a root resource in one of the class which implements javax.ws.rs.core.Application. This class acts as an entry point for rest and web resources.

How can I avoid the ServiceFilter class from being initialized twice? Or, is this okay as the filter implements both servlet and rest filters? Or, should I move the implementation in their own class files?

PS: The above stated behavior doesn't actually hinder any functionality offered by my application (I think and could be otherwise) but just wanted to make sure that I'm doing it right.

Tirath
  • 2,294
  • 18
  • 27
  • Make sure (by printing the 'toString' of your filter) that it is not logged twice!!! And did you configure it somewhere to **ALSO** be a resteasy enpoint? Then that might be the cause. It's illogical for something to both be a filter and a resteasy endpoint – Kukeltje Nov 20 '17 at 21:13
  • Not logged twice (updated description) and `ServiceFilter ` acts as a filter to resteasy endpoint(s). – Tirath Nov 21 '17 at 10:01
  • 1
    Effectively the situation is 'normal'.... The resteasy endpoint most likely has no knowledge of the filter annotations and the filter has no knowledge of the existence (somewhere) of a resteasy annotation. To prevent confusion, I'd split this in two classes and put al real service functionality in service classes. https://stackoverflow.com/questions/29982657/how-to-implement-jax-rs-restful-service-in-jsf-framework is about jax-rs vs jsf but the same is true for jax-rs vs servletfilters... – Kukeltje Nov 21 '17 at 10:06

0 Answers0