Search This Blog

Friday, 14 September 2012

Practical 22) Create a servlet filter that logs all access to and from servlets in an application and prints the following to System.out: a. the time the request was received b. the time the response was sent c. how much time it took to process the request d. the URL of the resource requested e. the IP address of the visitor


package def22;
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.util.*;

public class ReportFilter implements Filter
{
          ServletContext context;
          public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException
          {
                   HttpServletRequest request=(HttpServletRequest)req;
                   PrintWriter out=res.getWriter();
                   Date myreqdate=new Date();

                   try
                   {
                             Thread.sleep(100);
                   }
                   catch(Exception e)
                   {
                             out.println(e);
                   }


                   String mylog=new String(request.getRemoteHost()+"tried to access"+request.getRequestURL()+"cn Time"+new Date());
                   //System.out.println(mylog);
                   context.log(mylog);
                   chain.doFilter(req,res);

                   //System.out.println("Request receive cn"+myreqdate);
                   //context.log(myreqdate);
                   Date myresdate=new Date();
                   //System.out.println("Response receive cn"+myresdate);
                   //context.log(myresdate);

                   long diff =myresdate.getTime()-myreqdate.getTime();
                   context.log("Time tack to process diff is"+diff);

          }
          public void init(FilterConfig confy)
          {
                   context=confy.getServletContext();


          }

          public void destroy()
          {
          }

}

Output
Note: it’s output generate on console (tomcat server console ).

No comments:

Post a Comment