Java Web Implementation Filter Analysis the number of visits to the IP statistics website

Source: Internet
Author: User
Tags get ip

Statistical work needs to be performed before all resources are available, so it can be placed in the filter.

We are not going to intercept this filter! Because we are only used to do statistics.

Use something to load the statistic data. Map<string,integer>

The entire site only needs a map!

When the map was created (using Servletcontextlistener, it was created when the server was started, and only in ServletContext), where is the map saved to! (Map saved to ServletContext!!!) )

    • The map needs to be used to save the data in the filter
    • Map needs to be used on the page to print the data in the map

1 analysis

Because a site may have multiple pages, regardless of which page is accessed, the number of visits is counted, so it is most convenient to use filters.

Because of the need for IP statistics, you can create a map in the filter, using the IP key, the number of accesses is value. When there is a user access, obtain the requested IP, if the IP exists in the map, indicating the previous access, then add 1 to the number of visits, the IP in the map does not exist, then set the number of 1.

Store this map in ServletContext!

2 Code

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5" xmlns= "     Java ee "     xmlns:xsi=" "     xsi:schemalocation=" Xml/ns/javaee ">    <filter>    < Filter-name>myfilter</filter-name>    <filter-class>com.cug.filter02.myfilter</filter-class ></filter><filter-mapping>    <filter-name>MyFilter</filter-name>    < Url-pattern>/*</url-pattern></filter-mapping><listener>    <listener-class> Com.cug.filter02.mylistener</listener-class></listener></web-app>

Package Com.cug.filter02;import Java.util.linkedhashmap;import;import javax.servlet.ServletContext; Import Javax.servlet.servletcontextevent;import Javax.servlet.servletcontextlistener;public class MyListener    Implements servletcontextlistener{@Override public void contextdestroyed (Servletcontextevent arg0) {} @Override public void contextinitialized (Servletcontextevent arg0) {ServletContext context = Arg0.getservletc        Ontext ();        map<string, integer> ipMap = new linkedhashmap<string, integer> ();    Context.setattribute ("IpMap", IpMap); }}package com.cug.filter02;import;import;import javax.servlet.Filter;import Javax.servlet.filterchain;import Javax.servlet.filterconfig;import Javax.servlet.servletcontext;import Javax.servlet.servletexception;import Javax.servlet.servletrequest;import Javax.servlet.servletresponse;public Class Myfilter implements filter{private Filterconfig filtErconfig; @Override public void Destroy () {} @Override the public void DoFilter (ServletRequest request, SERVLETRESP Onse response, Filterchain chain) throws IOException, Servletexception {ServletContext context = Filter        Config.getservletcontext ();        map<string, integer> IpMap = (map<string, integer>) context.getattribute ("IpMap");        String IP = request.getremoteaddr ();            if (Ipmap.containskey (IP)) {Integer count = ipmap.get (IP);        Ipmap.put (ip,count+1);        }else{Ipmap.put (ip,1);        } context.setattribute ("IpMap", IpMap);    Chain.dofilter (request, response); } @Override public void init (Filterconfig filterconfig) throws servletexception {this.filterconfig = Filterc    Onfig; }}

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><% @taglib prefix= "C" uri= "/HTTP/ "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 


In the JSP, the method to obtain the client's IP address is:request.getremoteaddr (), this method is effective in most cases. However, the real IP address of the client cannot be obtained through the reverse proxy software such as Apache,squid. If reverse proxy software is used, the URL of the reversed to the URL of the, using therequest.getremoteaddr ()The IP address obtained by the method is: or, not the real IP of the client. After the agent, due to the addition of the middle tier between the client and the service, so the server can not directly get the client's IP, the server-side application can not directly forward the requested address to the client. However, the x-forwarded-for information is added to the HTTP header information of the forwarding request. Used to track the original client IP address and the server address of the original client request. When we visit, it is not that our browser actually accesses the index.jsp file on the server, but instead it is accessed by the proxy server first INDEX.JSP, the proxy server will return the results of the access to our browser, because it is the proxy server to access the index.jsp, so index.jsp throughrequest.getremoteaddr ()is actually the address of the proxy server, not the IP address of the client. The method of obtaining a client's real IP address can be obtained:
     Public  String getipaddr (httpservletrequest request)  {           string IP  =  request.getheader (" X-forwarded-for ");            if (IP  = =   Null   | |  Ip.length ()  = =   0   | |   "Unknown". Equalsignorecase (IP))  {               IP  =  Request.getheader ("Proxy-client-ip");           }             if (IP  = =   Null   | |  Ip.length ()  = =   0   | |   "Unknown". Equalsignorecase (IP))  {               IP  =  Request.getheader ("Wl-proxy-client-ip");           }             if (IP  = =   Null   | |  Ip.length ()  = =   0   | |   "Unknown". Equalsignorecase (IP))  {              IP  =  Request.getremoteaddr ();          }            return  IP;      }

Add: Finally, a python can be executed in the background to complete the statistics and analysis of the access address:

Not complete code
#-*-CODING:GBK-*-import urllib2import re url = ""% ipaddr u = urllib2.urlopen (URL) s = () #Get ip Address ip = re.findall (R ' \d{1,3}\.\d{1,3}\.\d{1,3}\.\d {1,3} ', s) print "\n****** Below Result from IP138 Database * * * * *" print "IP address:", ip[0] #Get IP address Lo cation result = Re.findall (R ' (<li>.*?</li>) ', s) for i in result: print i[4:-5] print "* "*45 print" \ n "

Java Web Implementation Filter Analysis the number of visits to the IP statistics website

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.