Here is a small example of getting info from a HttpServletRequest
using a ServletRequestListener
.
First, add the listener to the web.xml config file. This file should be located in the WEB-INF folder.
<listener>
<description>RequestListener</description>
<listener-class>web.MyRequestListener</listener-class>
</listener>
In the above configuration the
ServletRequestListener
named
MyRequestListener
is located in the
web
package.
Next, create MyRequestListener
in the web
package as follows.
package web;
import javax.servlet.*;
public class MyRequestListener implements ServletRequestListener {
public void requestInitialized(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest)event.getServletRequest();
System.out.println("request initialized");
System.out.println("Request Remote Addr = " + request.getRemoteAddr());
System.out.println("Request Remote Host = " + request.getRemoteHost());
System.out.println("Request Remote Port = " + request.getRemotePort());
java.util.Enumeration e = request.getAttributeNames();
while(e.hasMoreElements()) {
String attName = (String)e.nextElement();
Object val = request.getAttribute(attName);
System.out.println("Request Att (" + attName + ") = " + val.toString());
}
e = request.getParameterNames();
while(e.hasMoreElements()) {
String paramName = (String)e.nextElement();
Object val = request.getParameter(paramName);
System.out.println("Request Param (" + paramName + ") = " + val.toString());
}
e = request.getHeaderNames();
while(e.hasMoreElements()) {
String headerName = (String)e.nextElement();
Object val = request.getHeader(headerName);
System.out.println("Header (" + headerName + ") = " + val.toString());
}
}
public void requestDestroyed(ServletRequestEvent event) {
System.out.println("request destroyed");
}
}
All the code does is print out attributes, parameters, and info from the HTTP header. If you need the date for the request you can create a
java.util.Date
when
requestInitialized()
is entered.
Keep in mind that a ServletRequestListener
's requestInitialized()
will be called every time there is a HTTP request from a browser (or bot) so it may be better to use a tool external to your application to track usage. If you are looking for external tools you may want to consider Google Analytics, or Urchin if your network configuration does not allow you to use Google Analytics.