问题描述
在以下问题的接受答案中,有13K +代表的SO经常会建议使用网络错误(不可缓存的1x1 img)来跟踪日志中的请求:
如何在Java中执行此操作?
基本上,我有两个问题: 如何确保1x1图像不可缓存(如何设置标题)?
我正在寻找一段精确的代码,因为我知道如何写一个.jsp / servlet,我知道如何提供一个1x1图像:)
我的问题实际上是关于我应该编写的确切.jsp / servlet以及/例如我打算使用下面的映射:
pre> < servlet的映射>
< servlet-name> WebBugServlet< / servlet-name>
< url-pattern> / webbug *< / url-pattern>
< / servlet-mapping>
,然后使用引用webbug的 img 标签。 png(或.gif),那么我该如何编写.jsp / servlet?
我应该在日志中寻找什么/哪里?
简单的方法是将日期时间戳添加到JSP中的图像。这将防止图像被缓存。
<%
java.util.Date dt = new java。 util.Date();
%>
< img src =/ invisible.jpg?<%= dt.getTime()%> width =1height =1>
在您的访问日志中,您可以计算您的jpg - 输出应该是
127.0.0.1 - - [10 / Jun / 2010:11:38:53 +0530]GET /mywebapp/jsp/invisible.jpg? 1276150133362 HTTP / 1.1200 991
127.0.0.1 - - [10 / Jun / 2010:11:38:54 +0530]GET /mywebapp/jsp/invisible.jpg?1276150134659 HTTP / 1.1200 991
127.0.0.1 - - [10 / Jun / 2010:11:38:55 +0530]GET /mywebapp/jsp/invisible.jpg?1276150135627 HTTP / 1.1200 991
在这种方法中,您不需要servlet映射。
另一种方法是涉及编写一个Filter类来设置缓存控制标题。
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:
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?
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.
这篇关于Java webapp:如何实现一个网络bug(1x1像素)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!