public class OptionalFilter extends Object implements javax.servlet.Filter
Predicate
or Hamcrest Matcher
. The filter is
executed if the predicate or the matchers matches and skipped otherwise.
Define a predicate and wrap the base filter.
public class FrenchSomethingFilter extends OptionalFilter { public FrenchSomethingFilter() { super(new HasLocale(Locale.FRENCH), new SomethingFilter()); } }
Add the filter to your web.xml.
<filter> <filter-name>FrenchSomethingFilter</filter-name> <filter-class>your.package.FrenchSomethingFilter</filter-class> </filter> <filter-mapping> <filter-name>FrenchSomethingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
You can provide init-params that will be dispatched to the base filter.
You can use Lambda expressions as predicates if you're using Java 8.
public class FrenchSomethingFilter extends OptionalFilter { public FrenchSomethingFilter() { super( (request) -> request.getLocale().equals(Locale.FRENCH), new SomethingFilter()); } }
You can use Hamcrest Matcher
s as predicates.
public class FrenchSomethingFilter extends OptionalFilter { public FrenchSomethingFilter() { super( hasProperty("locale", equalTo(Locale.FRENCH)), new SomethingFilter()); } }
Constructor and Description |
---|
OptionalFilter(org.hamcrest.Matcher<? super javax.servlet.ServletRequest> matcher,
javax.servlet.Filter baseFilter) |
OptionalFilter(Predicate<? super javax.servlet.ServletRequest> predicate,
javax.servlet.Filter baseFilter) |
Modifier and Type | Method and Description |
---|---|
void |
destroy() |
void |
doFilter(javax.servlet.ServletRequest request,
javax.servlet.ServletResponse response,
javax.servlet.FilterChain filterChain) |
void |
init(javax.servlet.FilterConfig filterConfig) |
public OptionalFilter(Predicate<? super javax.servlet.ServletRequest> predicate, javax.servlet.Filter baseFilter)
public OptionalFilter(org.hamcrest.Matcher<? super javax.servlet.ServletRequest> matcher, javax.servlet.Filter baseFilter)
public void init(javax.servlet.FilterConfig filterConfig) throws javax.servlet.ServletException
init
in interface javax.servlet.Filter
javax.servlet.ServletException
public void doFilter(javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, javax.servlet.FilterChain filterChain) throws IOException, javax.servlet.ServletException
doFilter
in interface javax.servlet.Filter
IOException
javax.servlet.ServletException
public void destroy()
destroy
in interface javax.servlet.Filter
Copyright © 2014–2015. All rights reserved.