Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 398
  • Last Modified:

servlet filter

Hi,

I am trying below example
http://www.tutorialspoint.com/servlets/servlets-writing-filters.htm

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
 */
@WebFilter("/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
 chain.doFilter(request,response);
}

      /**
       * @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
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String message;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // 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
response.setContentType("text/html");

// 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";
else
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 " +
"transitional//en\">\n";
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


web.xml

<?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">
  <display-name>TutorialPointServletProj</display-name>
 
  <filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
        <param-name>test-param</param-name>
        <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>


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:

<filter-mapping>
   <filter-name>AuthenFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

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

Please advise
Any links resources ideas highly appreciated. Thanks in advance
0
gudii9
Asked:
gudii9
  • 4
  • 3
1 Solution
 
Ken ButtersCommented:
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.
0
 
gudii9Author Commented:
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.
0
 
Ken ButtersCommented:
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.

https://logging.apache.org/log4j/1.2/manual.html
https://logging.apache.org/log4j/1.2/index.html
0
Technology Partners: 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!

 
gudii9Author Commented:
Any working example end to end on how to configure and integrate with eclipse etc. please advise
0
 
Ken ButtersCommented:
Did you review the first link I gave you?

https://logging.apache.org/log4j/1.2/manual.html

It has a working example and end to end on how to configure it.
0
 
gudii9Author Commented:
Sure. Let me try and get back to you.
0
 
Ken ButtersCommented:
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.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now