Created
July 30, 2019 08:34
-
-
Save philippebn/999f5dd22d0d703d7534f46d6d68519e to your computer and use it in GitHub Desktop.
ParamWrapperFilter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.logging.log4j.LogManager; | |
import org.apache.logging.log4j.Logger; | |
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.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletRequestWrapper; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Enumeration; | |
import java.util.List; | |
import java.util.regex.Pattern; | |
public class ParamWrapperFilter implements Filter { | |
private Pattern pattern; | |
private static Logger logger = LogManager.getLogger(ParamWrapperFilter.class); | |
@Override | |
public void init(FilterConfig filterConfig) throws ServletException { | |
pattern = Pattern.compile(filterConfig.getInitParameter("excludeParams")); | |
} | |
@Override | |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { | |
chain.doFilter(new ParamFilteredRequest(request, pattern), response); | |
} | |
@Override | |
public void destroy() { | |
} | |
/** */ | |
private static class ParamFilteredRequest extends HttpServletRequestWrapper { | |
private final Pattern pattern; | |
ParamFilteredRequest(ServletRequest request, Pattern pattern) { | |
super((HttpServletRequest)request); | |
this.pattern = pattern; | |
} | |
@Override | |
public Enumeration<String> getParameterNames() { | |
List<String> requestParameterNames = Collections.list(super.getParameterNames()); | |
List<String> finalParameterNames = new ArrayList<>(); | |
for (String parameterName: requestParameterNames) { | |
if (!pattern.matcher(parameterName).matches()) { | |
finalParameterNames.add(parameterName); | |
} else { | |
logger.warn("parameters to exclude : {}", parameterName); | |
} | |
} | |
return Collections.enumeration(finalParameterNames); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment