1、后端controller包下添加方法
/** * 获取访问量 */ @CrossOrigin(origins = "*",maxAge = 3600) @GetMapping("/getViewCount") public int countBlog(HttpServletRequest request) { ServletContext context = request.getServletContext(); //从ServletContext中获取计数器对象 Integer count = (Integer) context.getAttribute("counter"); // 如果为空,则在ServletContext中设置一个计数器的属性 if (count == null) { count = 1; context.setAttribute("counter", count); } else { context.setAttribute("counter", count + 1); } System.out.println("访问次数 " + count); return count; }
2、前端请求获取访问量(vue)
//获取访问量 getviewCount(){ var _this = this this.axios.get('/blog/getViewCount').then(resp=>{ console.log(resp) _this.viewCount = resp.data //将获取到的访问量数值进行赋值 }).catch((error) => { //捕获异常 console.log(error) })
3、然后调用组件data中viewCount就可以显示了