Learning Notes _ Filter App _1 (number of visits to IP statistics website)

Source: Internet
Author: User

Number of visits to the IP statistics website





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 description

The website counts the number of times each IP address accesses this site.

2 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!  

3 Code



<table align="center" width="50%" border="1">


<th>ip Address </th>

<th> Times </th>


<c:foreach items= "${applicationscope.ipcountmap}" var="entry">






[Cui 1] </table>



Public class IPFilter implements Filter {

Private ServletContext context;

Public void init (filterconfig fconfig) throws servletexception {

context = Fconfig.getservletcontext (); [Cui 2] save ServletContext

map<string, integer> Ipcountmap = Collections

. Synchronizedmap (new linkedhashmap<string, integer> ()); [Cui 3] create a map and save it to ServletContext

Context.setattribute ("Ipcountmap", Ipcountmap);


@SuppressWarnings ("Unchecked")

Public void DoFilter (servletrequest request, servletresponse response,

Filterchain chain) throws IOException, servletexception {

HttpServletRequest req = (httpservletrequest) request;

String IP = req.getremoteaddr (); [Cui 4]

map<string, integer> Ipcountmap = (map<string, integer>) context

. getattribute ("Ipcountmap");

[Cui 5]

Integer count = Ipcountmap.get (IP); [Cui 6]

if (count = = null) {

Count = 1;

[Cui 7] } Else {

Count + = 1; [Cui 8] Otherwise add 1 to the original number of times


Ipcountmap.put (IP, count); [Cui 9] Set the IP and number of times to map

Context.setattribute ("Ipcountmap", Ipcountmap); [Cui] store the map in the context

Chain.dofilter (request, response); [Cui one] release!


Public void Destroy () {}











[Cui 1] loops through the map in ServletContext, where key is the IP address and value is the number of accesses

[Cui 2] save ServletContext

[Cui 3] create a map and save it to ServletContext

[Cui 4] get the requester's IP

[Cui 5] get map in context

[Cui 6] get the current IP access number in the map

[Cui 7] If this IP does not exist in the map, then set the access count to 1

[Cui 8] Otherwise add 1 to the original number of times

[Cui 9] set the IP and number of times to map

[Cui] store the map in the context

[Cui one] release!

Full code:


 PackageCn.itcast.web.filter;Importjava.io.IOException;ImportJava.util.Map;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;ImportJavax.servlet.ServletContext;Importjavax.servlet.ServletException;Importjavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;/*** Get map from Application * Get the current client's IP * from request and save the results to map *@authorCXF **/ Public classAfilterImplementsFilter {Privatefilterconfig config;  Public voiddestroy () {} Public void doFilter(servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {/** 1. Get the map * 2 in Application . Obtain the current client's IP address * 3 from request. Check to see if there is an IP corresponding access number in the map, and if so, save the number of times +1 back to * 4. If this IP is not present, then this is the first time to access the site, set the number of visits to 1*/        /** 1. Get appliction*/ServletContext App=Config.getservletcontext (); Map<String,Integer> map = (map<string, integer>) app.getattribute ("Map"); /** 2. Get the IP address of the client*/String IP=request. getremoteaddr        (); /** 3. Make judgments*/        if(Map.containskey (IP)) {//This IP exists in the map, stating that it is not the first time to access            intCNT =map.get (IP); Map.put (IP, CNT+1); } Else{//This IP does not exist in the map, it is the first time to visit           map.put (IP, 1); } App.setattribute ( "map", map); // Put the map back in the app Chain.dofilter (request, response); // sure release  .    }    /*** This method is executed when the server is started, and this method executes only once! */     Public voidInit (Filterconfig fconfig)throwsservletexception { This. config =Fconfig; }}


 PackageCn.itcast.web.listener;ImportJava.util.LinkedHashMap;ImportJava.util.Map;ImportJavax.servlet.ServletContext;Importjavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener; Public classAlistenerImplementsServletcontextlistener {/*** Create map at server startup, save to ServletContext */     Public voidcontextinitialized (Servletcontextevent sce) {//Create a map       map<string,integer> Map = new linkedhashmap<string,integer>(); //Get ServletContext        ServletContext application = sce.getservletcontext (); //Save the map to the applicationApplication.setattribute ("Map", map); Named map, can also be any other} Public voidcontextdestroyed (Servletcontextevent sce) {}}

Learning Notes Filter App _1 (number of visits to the IP statistics site)

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.