基于servlet实现统计网页访问次数

网友投稿 247 2022-08-29


基于servlet实现统计网页访问次数

本文实例为大家分享了基于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.setCharacterEncohttp://ding("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.seDkeNotAttribute("count", count);

}else {

//否则就不是第一次访问,将登陆的计数器进行加1的数据更新

servletContext.setAttribute("count", count+1);

}

//将登陆的次数显示在页面上

PrintWriter out =response.getWriter();

out.print("\r\n" +

"\r\n" +

"

"\r\n" +

"

"\r\n" +

"

out.print("

out.print("您是第 "+ servletContext.getAttribute("count")+"位访客");

out.print("

out.print("\r\n" +

"

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpDkeNoServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

doGet(request, response);

}

}

三、在不同浏览器显示的次数

(1)在eclipse中显示的次数

(2)在火狐中显示的次数

(3)在360中显示的次数


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python标识符规则、关键字、特殊变量操作实例(python中合法标识符举例)
下一篇:Python模块结构与布局操作实例(python项目结构设计)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~