package cn.xijie.listener;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
public class CallListener implements ServletRequestListener {
private static Map<String, String> map = new HashMap<String, String>();
// 实例变量提供访问页面流量使用
private int counter;
static {
map.put("127.0.0.1", "北京");
map.put("192.168.11.96", "深圳");
map.put("192.168.11.113", "中山");
map.put("192.168.11.124", "珠海");
}
//线程共享
@Override
public void requestInitialized(ServletRequestEvent sre) {
//如果不加会有线程安全问题 ;每个线程共享的变量才加锁
synchronized (this) {
this.counter++;
}
// 取得事件源,即ServletRequest对象
HttpServletRequest request = (HttpServletRequest) sre
.getServletRequest();
// 取得客户端IP
String ip = request.getRemoteAddr();
// 通过ip查询归属地
String address = map.get(ip);
if (address == null) {
address = "北京";
}
// 通过ip查询归属地
request.setAttribute("ip", ip);
request.setAttribute("address", address);
request.setAttribute("counter",this.counter);
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
}
}
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function startTime(){
//每隔1秒钟执行updateTime()方法
window.setInterval("updateTime()",1000);
}
function updateTime(){
//取得当前时间
var date = new Date();
//取得当前时间的本地描述信息
var msg = date.toLocaleString();
//定位spanID所指定的区域
var spanElement = document.getElementById("spanID");
//将信息写入span标签内部[JS大小写是不同的含义]
spanElement.innerHTML = msg;
}
</script>
</head>
<body onload="startTime()">
你的IP地址:${requestScope.ip}<br/>
归属地:${requestScope.address}<br/>
当前流量,即访问当前jsp的次数:${requestScope.counter}<br/>
当前时间:<span id="spanID"></span>
</body>
</html>
原文地址:http://blog.51cto.com/357712148/2105697