views:

94

answers:

1

In the accepted answer in the following question, a SO regular with 13K+ rep suggests to use a "web bug" (non-cacheable 1x1 img) to be able to track requests in the logs:

http://stackoverflow.com/questions/1784893

How can I do this in Java?

Basically, I've got two issues:

  • how to make sure the 1x1 image is not cacheable (how to set the header)?

  • how to make sure the query for these 1x1 image will appear in the logs?

I'm looking for exact piece of code because I know how to write a .jsp/servlet and I know how to serve an 1x1 image :)

My question is really about the exact .jsp/servlet that I should write and how/what needs to be done so that Tomcat logs the request.

For example I plan to use the following mapping:

<servlet-mapping>
        <servlet-name>WebBugServlet</servlet-name>
        <url-pattern>/webbug*</url-pattern>
</servlet-mapping>

and then use an img tag referencing a "webbug.png" (or .gif), so how do I write the .jsp/servlet?

What/where should I look for in the logs?

+3  A: 

The simple method is to add the date timestamp to the image in the JSP. This will prevent the image from getting cached.

<%
java.util.Date dt = new java.util.Date ();
%>
<img src="/invisible.jpg?<%=dt.getTime ()%>" width="1" height="1">

In your access logs, you can count for your jpg - the output should be

127.0.0.1 - - [10/Jun/2010:11:38:53 +0530] "GET /mywebapp/jsp/invisible.jpg?1276150133362 HTTP/1.1" 200 991
127.0.0.1 - - [10/Jun/2010:11:38:54 +0530] "GET /mywebapp/jsp/invisible.jpg?1276150134659 HTTP/1.1" 200 991
127.0.0.1 - - [10/Jun/2010:11:38:55 +0530] "GET /mywebapp/jsp/invisible.jpg?1276150135627 HTTP/1.1" 200 991

In this approach, you wont need the servlet mapping.

The alternate approach will involve writing a Filter class to set cache-control headers.

JoseK