1. 程式人生 > >RequestListener 學習筆記-記錄來訪者IP

RequestListener 學習筆記-記錄來訪者IP

RequestListener 學習筆記

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>

技術分享圖片

RequestListener 學習筆記-記錄來訪者IP