Example program to demonstrate Logging Filter
This example illustrates how one can write Logging Filter servlet to provide control over log file. You can have additional controls over these log files and these all are available to use by implementing "Filter" class. Filters are very important in servlet access and handling due to number of reasons, for example, it encapsulates recurring tasks in a reusable unit, modularizing codes so that they become easy to manage, transforming request from a servlet to JSP page. Most common task for a web application is to format data sent back to client since most clients require different format (e.g in WML,XML etc.) rather than only HTML so to accomplish these tasks of clients, Filtering is important to develop a fully featured Web Application. Filters can perform many different tasks, in which logging is one of the most important task. You can create filter class by implementing javax.servlet.Filter, which has three methods as follows:
init(FilterConfig) is called once by the server to get prepared for service and then it calls doFilter() number of times for request processing.
In this example there is LoggingFilterExample servlet which is writing Remote Address, URI , Protocol of calling JSP file into log file as server calls LoggingFilterExample via logging.jsp. Source code for LoggingFilterExample.java is given as below:
LoggingFilterExample writes content in log file by the following method:
|<%@ page language="java" %>
<title>Logging Filter Example</title>
This filter writes log file of Tomcat Web Server.
See log file of Web server.
When this JSP file is called by the server then through the filter mapping LoggingFilterExample filter would be called and it will write content into log file of your web server. To do working we have to do mapping in the web.xml deployment descriptor. <filter> and <filter-mapping> element requires <filter-name> to tell the name of filter to which you want to map a servlet or URL pattern. This mapping is as follows:
|<?xml version="1.0" encoding="ISO-8859-1"?>
<display-name>Welcome to Tomcat</display-name>
<description>Welcome to Tomcat</description>
To run this example you have to follow these few steps given as below:
By typing above URL, the opened page would be like this
and now go and see your tomcat's logs/localhost.<current date>.log file. Last few lines in this file would be like this.
Liked it! Share this Tutorial