Logging HTTP Request Parameters using HTTP Servlet

This is a servlet filter that i use if i want to log what parameters fired by my REST client, basically it’s just a simple http servlet filter.

package com.edw;

import java.io.IOException;
import java.util.Enumeration;
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 org.apache.log4j.Logger;

public class LoggingFilter implements Filter {

    private Logger logger = Logger.getLogger(this.getClass());
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            
            String uri = req.getRequestURI();
            logger.debug("Requested Resource::"+uri);
            
            Enumeration<String> enumeration = req.getParameterNames();
            
            while(enumeration.hasMoreElements()) {
                String parametername = enumeration.nextElement();
                logger.debug(parametername + " : " +req.getParameter(parametername));
            }
        } catch (Exception e) {
            logger.error(e,e);
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}

Add your servlet filer to your web.xml and listen for a specific url request, on this example i listen for requests to /services/ url.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">    
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <filter>
	<filter-name>LogFilter</filter-name>
	<filter-class>
		com.edw.LoggingFilter
	</filter-class>
    </filter>
    <filter-mapping>
            <filter-name>LogFilter</filter-name>
            <url-pattern>/services/*</url-pattern>
    </filter-mapping>    
</web-app>
Google+

No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)