servlet filter

Posted on 2014-02-23
Medium Priority
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.io.IOException;
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 java.io.IOException, 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);

package com.tp.first;

import java.io.IOException;
import java.io.PrintWriter;
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="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 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 2000 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.

Command Line Tips and Tricks

The command line is a powerful tool at the disposal of every Linux user. Although Linux distros come with beautiful user interfaces, it's worthwhile to learn the command line because it allows you to do a number of things that you otherwise cannot do from the GUI.  


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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month10 days, 14 hours left to enroll

770 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