RequestListener 学习笔记-记录来访者IP

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RequestListener 学习笔记-记录来访者IP相关的知识,希望对你有一定的参考价值。


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的主要内容,如果未能解决你的问题,请参考以下文章

JavaEE企业应用实战学习记录requestListener

博客说明

教你认识你的访客

node.js createserver获取请求值

如何做日志分析

欢迎来访个人网站——阳光日志