Solved

servlet filter

Posted on 2014-02-23
7
369 Views
Last Modified: 2014-03-26
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
Comment
Question by:gudii9
  • 4
  • 3
7 Comments
 
LVL 19

Expert Comment

by:Ken Butters
Comment Utility
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
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
 
LVL 19

Accepted Solution

by:
Ken Butters earned 500 total points
Comment Utility
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 7

Author Comment

by:gudii9
Comment Utility
Any working example end to end on how to configure and integrate with eclipse etc. please advise
0
 
LVL 19

Expert Comment

by:Ken Butters
Comment Utility
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
 
LVL 7

Author Comment

by:gudii9
Comment Utility
Sure. Let me try and get back to you.
0
 
LVL 19

Expert Comment

by:Ken Butters
Comment Utility
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 your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now