Record website visits

1. Create a table in the database to store the hits

2. Create a listener (MyWebListener) to implement the ServletContextListener interface. When the project is started, the hits are obtained through the dao layer (ContextMapper) and stored in the ServletContext.

3. Increase the number of visits when visiting the home page

4. The front end gets the hits or stores the hits into the database (ContextController) before the project is closed

database

create table context(
	click_num int
)

dao layer

Interface

public interface ContextMapper {
    Integer selectClickNum();

    int updateClickNum(Integer clickNum);
}

xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Package name.ContextMapper">
    <select id="selectClickNum" resultType="java.lang.Integer">
        select click_num
        from context
    </select>

    <update id="updateClickNum" parameterType="java.lang.Integer">
        update context
        set click_num = #{clickNum, jdbcType=INTEGER}
    </update>
</mapper>

monitor

import cn.javak.mapper.ContextMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

@Component
public class MyWebListener implements ServletContextListener {
    @Autowired
    private ContextMapper contextMapper;
    private static final Logger logger = LoggerFactory.getLogger(MyWebListener.class);
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        logger.info("Project initialization variables");
        ServletContext context = sce.getServletContext();
        Integer clickNum = null;
        try {
            clickNum = contextMapper.selectClickNum();
            context.setAttribute("clickNum",clickNum);
            logger.info("Initialize site hits"+clickNum);
        }catch (Exception e){
            logger.error("Failed to get hits", e);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("Project termination");
    }
}

Insert the following code when visiting the home page

//Increase the number of hits
ServletContext context = request.getServletContext();
Integer clickNum = (Integer) context.getAttribute("clickNum");

Provide website traffic interface

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.PreDestroy;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/context")
public class ContextController {
    @Autowired
    private ContextMapper contextMapper;
    @Autowired
    private WebApplicationContext webApplicationConnect;

    private static final Logger logger = LoggerFactory.getLogger(ContextController.class);

    @GetMapping("/clickNum")
    public JSONObject getClickNum(HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        Integer clickNum = (Integer) context.getAttribute("clickNum");
        JSONObject obj = new JSONObject();
        obj.put("status","success");
        obj.put("msg","Access to the website was successful");
        obj.put("clickNum", clickNum);
        return obj;
    }

    /**
     * Update website hits before project closure
     */
    @PreDestroy
    public void destroy() {
        Integer clickNum = (Integer) webApplicationConnect.getServletContext().getAttribute("clickNum");
        contextMapper.updateClickNum(clickNum);
        logger.info("Update hits succeeded" + clickNum);
    }
}

Front end ajax

url = function (i) {
    //Project path
    return "http://localhost:8080/" + i;
};
loadClickNum = function () {
    $.ajax({
        type: 'get',
        url: url("context/clickNum"),
        cache: false,
        dataType: 'json',
        success: function (data) {
            //Gets the id of the element that displays the hits
            $("#clickNum").text(data.obj.clickNum);
        }
    });
};

Tags: Database Mybatis xml Java

Posted on Tue, 30 Jun 2020 02:50:41 -0400 by Derokorian