基于servlet实现统计网页访问次数
程序员文章站
2022-01-03 10:00:45
本文实例为大家分享了基于servlet实现统计网页访问次数的具体代码,供大家参考,具体内容如下一、基础知识(1)servletcontext和servletconfig的区别servletcontex...
本文实例为大家分享了基于servlet实现统计网页访问次数的具体代码,供大家参考,具体内容如下
一、基础知识
(1)servletcontext和servletconfig的区别
servletcontext作为整个web应用的共享数据
servletconfig只是作为当前servlet的数据共享,下一个servlet访问时,是访问不到的
二、代码实现
将显示的统计次数显示在html页面上:
import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletcontext; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; /** * servlet implementation class countservlet1 */ @webservlet("/countservlet1") public class countservlet1 extends httpservlet { private static final long serialversionuid = 1l; /** * @see httpservlet#httpservlet() */ public countservlet1() { super(); // todo auto-generated constructor stub } /** * @see httpservlet#doget(httpservletrequest request, httpservletresponse response) */ protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //设置字符编码 request.setcharacterencoding("utf-8"); response.setcharacterencoding("utf-8"); response.setcontenttype("text/html; charset=utf-8"); //获取全局的共享数据 servletcontext servletcontext = this.getservletcontext(); //获取计数器count integer count = (integer) servletcontext.getattribute("count"); //如果获取的计算器对象为空 ,说明是第一次访问,并将count,放入servletcount if( servletcontext.getattribute("count") == null) { count = 1; servletcontext.setattribute("count", count); }else { //否则就不是第一次访问,将登陆的计数器进行加1的数据更新 servletcontext.setattribute("count", count+1); } //将登陆的次数显示在页面上 printwriter out =response.getwriter(); out.print("<!doctype html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"utf-8\">\r\n" + "<title>登陆网页次数统计</title>\r\n" + "</head>\r\n" + "<body>"); out.print("<h1>"); out.print("您是第 "+ servletcontext.getattribute("count")+"位访客"); out.print("<h1>"); out.print("</body>\r\n" + "</html> } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub doget(request, response); } }
三、在不同浏览器显示的次数
(1)在eclipse中显示的次数
(2)在火狐中显示的次数
(3)在360中显示的次数
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: JSP实现简单网页计算器