Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Decorator pattern with HttpServerRequest
public class HttpServletRequestDecoratorFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
//do nothing
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request = decorate(request);
chain.doFilter(request, response);
private ServletRequest decorate(ServletRequest request) {
try {
HttpServletRequest req = (HttpServletRequest) request;
return new XFFAwareReq(req);
catch (ClassCastException e) {
// As we are not able to cast the request to an Http one, we just return the same object
return request;
public void destroy() {
// Do nothing
public class XFFAwareReq extends HttpServletRequestWrapper {
public XFFAwareReq(HttpServletRequest request) {
public String getRemoteAddr() {
String xff = getXForwardedFor();
return xff != null ? xff : super.getRemoteAddr();
public String getXForwardedFor() {
String xff = getHeader("X-Forwarded-For");
if (xff == null || "".equals(xff)) return null;
return getIpFromXFF(xff);
protected static final String getIpFromXFF(String xff) {
//extract and return the ip from the X-Forwarded-For header
public class XSSAwareReq extends HttpServletRequestWrapper {
protected XSSAwareReq(HttpServletRequest req) {
public String getParameter(String name) {
return super.getParameter(name)
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll("\\(", "&#40;")
.replaceAll("\\)", "&#41;")
.replaceAll("'", "&#39;")
.replaceAll("eval\\((.*)\\)", "")
.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"")
.replaceAll("script", "");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.