这篇文章主要介绍如何使用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("<h2>"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print("<h2>"); 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中显示的次数
以上是“如何使用servlet实现统计网页访问次数”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。