servlet filter

Posted on 2014-02-23
Last Modified: 2014-03-26

I am trying below example

I see output like
Feb 23, 2014 9:32:40 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\software\apache-maven-3.1.1\bin;C:\Program Files\Java\jdk1.6.0_41\bin;;C:\software\eclipse-jee-juno-SR1-win32\eclipse;;.
Feb 23, 2014 9:32:40 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:TutorialPointServletProj' did not find a matching property.
Feb 23, 2014 9:32:40 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 23, 2014 9:32:40 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 23, 2014 9:32:40 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1112 ms
Feb 23, 2014 9:32:40 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 23, 2014 9:32:40 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.52
Test Param: Initialization Paramter
Feb 23, 2014 9:32:41 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Feb 23, 2014 9:32:41 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 23, 2014 9:32:41 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 897 ms
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:15 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:20 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:25 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:30 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:35 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:40 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:45 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:50 EST 2014
IP 0:0:0:0:0:0:0:1, Time Sun Feb 23 21:33:55 EST 2014

My code looks like

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;

 * Servlet Filter implementation class LogFilter
public class LogFilter implements Filter {

     * Default constructor.
    public LogFilter() {
        // 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, ServletException {

 // Get the IP address of client machine.  
 String ipAddress = request.getRemoteAddr();

 // Log the IP address and current timestamp.
 System.out.println("IP "+ ipAddress + ", Time "
                                  + new Date().toString());

 // Pass request back down the filter chain

       * @see Filter#init(FilterConfig)
         public void  init(FilterConfig config)
               throws ServletException{
// Get init parameter
String testParam = config.getInitParameter("test-param");

//Print the init parameter
System.out.println("Test Param: " + testParam);


import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;

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 HelloWorld
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String message;
     * @see HttpServlet#HttpServlet()
    public HelloWorld() {
        // TODO Auto-generated constructor stub

	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    public void init() throws ServletException
        // Do required initialization
        message = "Hello World";

    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
    throws ServletException, IOException
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);

// Set response content type

// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
am_pm = "PM";

String CT = hour+":"+ minute +":"+ second +" "+ am_pm;

PrintWriter out = response.getWriter();
String title = "Auto Refresh Header Setting";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n");
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    // Method to handle POST method request.
    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException {
       doGet(request, response);


Open in new window


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">
        <param-value>Initialization Paramter</param-value>

Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4J logger to log above log in a separate file.

My question is how to use log4j to see in a file.
Using Multiple Filters:
Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you need to create a different mapping as mentioned below:

How to run multiple filters. I do not see complete code for that. can you please point me to link or complete code to do that.

For example, above example would apply LogFilter first and then it would apply AuthenFilter to any servlet but the following example would reverse the order:



What is meaning of reversing order. How they are doing it here.

Please advise
Any links resources ideas highly appreciated. Thanks in advance
Question by:gudii9
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 19

Expert Comment

by:Ken Butters
ID: 39883105
You have several unrelated questions in this question...

Are you wanting to understand log4j or filters?

When the questions are unrelated and on completely different topics, you should probably open different questions rather than copying and pasting examples and asking a multitude of questions on the copied source code.

Author Comment

ID: 39954262
Actually this question i would like to understand how to configure the log4j for this example. Please advise Multiple filters i will ask separate question.
LVL 19

Accepted Solution

Ken Butters earned 500 total points
ID: 39954288
The following website gives an introduction on log4j.
Please review the material here, and then let me know if that answers your question.  

Breifly, Log4j is a package that you can download and use in your code that will allow you to write out any data to a log file.  Log files are commonly used in java for debugging purposes.
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.


Author Comment

ID: 39954373
Any working example end to end on how to configure and integrate with eclipse etc. please advise
LVL 19

Expert Comment

by:Ken Butters
ID: 39954564
Did you review the first link I gave you?

It has a working example and end to end on how to configure it.

Author Comment

ID: 39956624
Sure. Let me try and get back to you.
LVL 19

Expert Comment

by:Ken Butters
ID: 39956766
You can see by the information at the link that there is a lot of information on log4j.  It would be difficult in a single question to answer everything about log4j.   After you review, please post back a specific question regarding log4j.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Configure a Bean in an XML file 4 49
servlet web applications   metadata-complete="true" or false 3 201
jboss 7.1 start up error 1 63
Crystal Reports Licensing Questions 4 63
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
This video teaches viewers about errors in exception handling.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question