java---Filter, the website counts the number of times each IP address visits this website

Problem-solving ideas:

Because a website may have multiple pages, no matter which page is visited, the number of visits must be counted, so it is most convenient to use filters.

Because you need to divide IP statistics, you can create a Map in the filter, using IP as the key and the number of visits as the value. When a user visits, get the requested IP. If the IP exists in the Map, it means that you have visited before. Then add 1 to the number of visits. If the IP does not exist in the Map, then set the number of times to 1.

CountFilter filter code:

@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() {
    
    

    }
}

The code of the jsp page:

<%@ 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>

Effect display:
Insert picture description here
If others visit your page, pay attention to give your ip to others, so that others can also visit!

Guess you like

Origin blog.csdn.net/weixin_44889894/article/details/114010755