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= "http://java.sun.com/xml/ns/     Java ee "     xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "     xsi:schemalocation=" http://java.sun.com/ Xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">    <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 Java.util.map;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 java.io.ioexception;import Java.util.map;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/ Java.sun.com/jsp/jstl/core "%><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 

Attention:

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 http://192.168.1.110:2046/is reversed to the URL of the http://www.xxx.com/, using therequest.getremoteaddr ()The IP address obtained by the method is: 127.0.0.1 or 192.168.1.110, 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 http://www.xxx.com/index.jsp/, 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 http://192.168.1.110:2046/ 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 = "http://www.ip138.com/ips138.asp?ip=%s&action=2"% ipaddr u = urllib2.urlopen (URL) s = u.read () #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

Related Article

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: info-contact@alibabacloud.com 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.