最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Servlet实现统计页面访问次数功能代码实例
时间:2022-06-29 02:32:21 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下Servlet实现统计页面访问次数功能代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
实现思路:
1.新建一个CallServlet类继承HttpServlet,重写doGet()和doPost()方法;
2.在doPost方法中调用doGet()方法,在doGet()方法中实现统计网站被访问次数的功能,用户每请求一次servlet,使得访问次数times加1;
3.获取ServletContext,通过它的功能记住上一次访问后的次数。
在web.xml中进行路由配置:
call //CallServlet为处理前后端交互的后端类CallServlet call /call
CallServlet类:
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created with IntelliJ IDEA
* Details about unstoppable_t:
* User: Administrator
* Date: 2021-04-07
* Time: 14:57
*/
//获得网站被访问的次数
public class CallServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
ServletContext context = getServletContext();
Integer times = (Integer) context.getAttribute("times");
if (times == null) {
times = new Integer(1);
} else {
times = new Integer(times.intValue() + 1);
}
PrintWriter out= resp.getWriter();
out.println("");
out.println("页面访问统计");
out.println(" ");
out.println("当前页面被访问了");
out.println(""+times+"次");
context.setAttribute("times",times);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
前端展示结果:
相关文章
- 暗喻幻想:ReFantazio召唤龙神条件说明 10-29
- 燕云十六声鲮货郎怎么解锁-鲮货郎经营解锁方法 10-29
- 暗喻幻想:ReFantazio召唤狮鹫王条件说明 10-29
- 暗喻幻想找玛丽亚聊旅途见闻任务攻略 10-29
- 暗喻幻想:ReFantazio新世界旅行记阅读攻略 10-29
- 暗喻幻想:ReFantazio召唤不死王条件说明 10-29

