# Java Filter for logging

In 
Published 2022-12-03

This tutorial will provide you with a short example where a Java Filter logs the incoming requests.

Servlet Filters are Java classes that can be used for intercepting requests from a client before they access a resource and for manipulating responses from server before they are sent back to the client. Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters.

In the following example I will intercept a request and I will audit MyJavaServlet calls.

First, you have to create an HTML page. Let's define it as an index page into the Web Dynamic Project:

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>From this page you call a Java servlet using POST Method</title>
</head>

<body>
   <form action="MyJavaServlet" method="POST">
        Name: <input type="text" name="name"> <br />
        Telephone#: <input type="text" name="telephone" />
                  <input type="submit" value="Submit" />
   </form>
</body>
</html>

Here is the web.xml file:

NOTES:

  • the name of the filter is not important for the configuration of the filter, but is important to understand why is created.
  • url-pattern tag is used to activate that filter for the Servlets that fit to that URL pattern.
  • filter-class tag is used to point to the class (code) that implement that filter.
  • if 2 filters will apply to a Servlet the order will be established by the filter mapping order in the web.xml file.
  • the Filters could be added or removed without changing the existing Java code.

And here is the code (the example) of my Java servlet which respond to a POST Method call :

MyJavaServlet.java
package servlets;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class MyJavaServlet
 */
@WebServlet("/MyJavaServlet")
public class MyJavaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyJavaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
 
        PrintWriter myResponse = response.getWriter();
        String message = "This is your response from a POST call. <br> The response is a Java Servlet !";
             
     
        myResponse.println( "\n" +"<title> Example of using Java Servlet with POST Call Method !</title>\n" +
             "\n" +
             "<h2 align="\"center\"">" + message + "</h2>\n" +
             "<ul>\n" +
             "  <li><b>You entered the name </b>: "       + request.getParameter("name") + "\n" +
             "  </li><li><b>You entered the telephone# </b>: " + request.getParameter("telephone") + "\n" +
             "</li></ul>\n" +
             "");
    }
}

And here is the code of the Java Filter :

package filters;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
 
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.HttpServletRequest;
 
/**
 * Servlet Filter implementation class MyFilter
 */
@WebFilter("/MyFilter")
public class MyFilter implements Filter {
 
    /**
     * Default constructor. 
     */
    public MyFilter() {
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }
 
    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here
 
        HttpServletRequest req = (HttpServletRequest) request;
          
        String servletPath = req.getServletPath();
        String remoteAddr = request.getRemoteAddr();
  
        System.out.println(" ");
        System.out.println("Logging Date: " + new Date());
        System.out.println("Servlet path: " + servletPath );
        System.out.println("Call from : " + remoteAddr);
         
        // pass the request along the filter chain
        chain.doFilter(request, response);
 
    }
 
    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }
}

When you run the index page you will see :

And when you press the "Submit" button you will see the page generated by the servlet :

Take a look into the console content (messages) and you will see: