java---Filter过滤器,网站统计每个IP地址访问本网站的次数

解题思路:

因为一个网站可能有多个页面,无论哪个页面被访问,都要统计访问次数,所以使用过滤器最为方便。

因为需要分IP统计,所以可以在过滤器中创建一个Map,使用IP为key,访问次数为value。当有用户访问时,获取请求的IP,如果IP在Map中存在,说明以前访问过,那么在访问次数上加1,即可;IP在Map中不存在,那么设置次数为1。

CountFilter过滤器代码:

@WebFilter("/*")
public class CountFilter implements Filter {
    
    
    private HashMap<String, Integer> map;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        //初始化map
        map = new HashMap<>();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    
    
        //最大的域对象
        ServletContext app = request.getServletContext();
        //获取ip
        String ip = request.getRemoteAddr();
        //判断map中是否存在这个ip
        if (map.containsKey(ip)){
    
    
            map.put(ip,map.get(ip)+1);
        }else {
    
    
            map.put(ip,1);
        }
        app.setAttribute("map",map);
        //放行
        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {
    
    

    }
}

jsp页面的代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>访问次数统计</h3>
<table align="center" border="1" width="60%">
    <tr>
        <th>ip</th>
        <th>次数</th>
    </tr>
	<%--拿到域中的map集合,遍历--%>
    <c:forEach var="m" items="${applicationScope.map}">
        <tr>
            <td>${
    
    m.key}</td>
            <td>${
    
    m.value}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

效果展示:
在这里插入图片描述
如果别人访问你的页面时,注意把自己的ip给到别人,这样就让别人也能够访问!

猜你喜欢

转载自blog.csdn.net/weixin_44889894/article/details/114010755