关于统计页面停留时间的一点小思路

首先,我们前端可以对后台发起一次ajax请求,来获取本次访问的一个唯一ID:

@Autowired
    private StayTimeService stayTimeService;
    @GetMapping("/id")
    public Object in(HttpServletRequest request, @RequestParam("url") String url){
        String ip=request.getRemoteHost();
        StayTime stayTime=new StayTime();
        stayTime.setIp(ip);
        stayTime.setUrl(url);
        stayTime.setTime(new Date());
        stayTime.setResidenceTime(0);
        return stayTimeService.recordAndGetId(stayTime);
    }

我们可以通过如上代码对一次页面请求进行记录,并返回一个唯一的ID。

然后呢,前台通过一次ajax请求获取ID:

$.ajax({
   url:"/ws/stayTime/id?url="+url,
    headers:{"Blog":"Restful"},
    success:function(data){
        id=data;
        console.log("取回ID成功,:"+id);
        heartBeat();
    }
    ,
    error:function(data){
       console.log("取回ID失败,原因"+data.status);
    }

});

如果取到了ID之后,我们就可以通过轮询的方式,相隔一定的时间根据ID发起请求,然后后端根据ID更新相应的记录

function heartBeat(){
    //定时给服务器发送心跳
    setInterval(function(){
        $.ajax({
            url:"/ws/stayTime/per/"+id,
            headers:{"Blog":"Restful"},
            success:function(data){
                console.log("心跳成功,:"+data);
            }
            ,
            error:function(data){
                console.log("心跳失败,原因"+data.status);
            }

        });
    },10000);
}

我的思路就是这样。

猜你喜欢

转载自blog.csdn.net/MY9526/article/details/82259727
今日推荐