package web.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionListener;
import java.util.LinkedHashMap;
import java.util.Map;
@WebListener()
public class AListener implements ServletContextListener,
HttpSessionListener, HttpSessionAttributeListener {
/*
* 在服务启动时创建Map,保存到ServletContext
* */
public void contextInitialized(ServletContextEvent sce) {
//创建Map
Map<String,Integer> map = new LinkedHashMap<String, Integer>();
//得到ServletContext
ServletContext application = sce.getServletContext();
application.setAttribute("map",map);
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
1 package web.filter;
2
3 import javax.servlet.*;
4 import javax.servlet.annotation.WebFilter;
5 import java.io.IOException;
6 import java.util.Map;
7
8 /*
9 * 从application中获取Map
10 * 从request中得到当前客户端的IP
11 * 进行统计工作,结果保存到Map中
12 * */
13 @WebFilter(filterName = "AFilter",urlPatterns = "/*")
14 public class AFilter implements Filter {
15 private FilterConfig config;
16 public void destroy() {
17 }
18
19 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
20 /*
21 * 1、得到application中的map
22 * 2、从request中获取当前客户端的IP地址
23 * 3、查看map中是否存在这个IP对应访问次数,如果存在,把次数+1再保存回去
24 * 4、如果不存在这个IP,那么说明是第一次访问本站,设置访问次数为1
25 * */
26 /*
27 * 1、得到application
28 * */
29 ServletContext app = config.getServletContext();
30 Map<String,Integer> map = (Map<String,Integer>) app.getAttribute("map");
31 /*
32 * 2、得到客户端的ip地址
33 * */
34 String ip = req.getRemoteAddr();
35 /*
36 *3、进行判断
37 * */
38 if (map.containsKey(ip)) {
39 int cnt = map.get(ip);
40 map.put(ip,cnt+1);
41 }else {
42 map.put(ip,1);
43 }
44 app.setAttribute("map",map);
45
46 chain.doFilter(req, resp);//肯定放行
47 }
48 /*
49 * 在服务器启动时就会执行本方法,而且本方法只执行一次
50 * */
51 public void init(FilterConfig config) throws ServletException {
52 this.config= config;
53 }
54 }
1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2 <%--
3 Created by IntelliJ IDEA.
4 User: Mac
5 Date: 13/09/2017
6 Time: 12:37 PM
7 To change this template use File | Settings | File Templates.
8 --%>
9 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
10 <html>
11 <head>
12 <title>Title</title>
13 </head>
14 <body>
15 <h1>显示结果</h1>
16 <table align="center" width="60%" border="1">
17 <tr>
18 <td>ip</td>
19 <td>次数</td>
20 </tr>
21 <c:forEach items="${applicationScope.map}" var="entry">
22 <tr>
23 <td>${entry.key}</td>
24 <td>${entry.value}</td>
25 </tr>
26 </c:forEach>
27 </table>
28 </body>
29 </html>