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) {
// 取得事件源,即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);
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
}
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP ‘index.jsp‘ starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
您的IP地址:${ip }<br/>
归属地:${requestScope.address}<br/>
</body>
</html>
原文地址:http://blog.51cto.com/357712148/2105691