博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Servlet学习的两个案例之网站访问次数的统计
阅读量:4678 次
发布时间:2019-06-09

本文共 2093 字,大约阅读时间需要 6 分钟。

一、统计次数的Servlet源码
package com.shanrengo;import java.io.IOException;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 用戶訪問countServlet,訪問次數+1 * 1.在countServlet初始化的時候,向ServletContext中保存一個訪問次數0 * @author Administrator * */public class CountServlet extends HttpServlet {	@Override	public void init() throws ServletException {		// TODO Auto-generated method stub		//向ServletContext保存訪問次數0		//ServletContext 中setAttribute方法		//1.獲得servletContext對象		ServletContext context = getServletContext();		//2.保存數據		context.setAttribute("visitTimes", 0);			}		public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		//每次訪問都會執行doGet		//1.從servletContext中獲得visitTimes		ServletContext context = getServletContext();		int times = (Integer) context.getAttribute("visitTimes");		//2.將visitTimes++		times++;		//3.更新		context.setAttribute("visitTimes", times);		System.out.println("網站被訪問了一次!");	}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		doGet(request, response);	}}

 

二、显示统计次数的servlet源码

package com.shanrengo;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class CountShowServlet extends HttpServlet {	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		ServletContext context = getServletContext();		int times = (Integer) context.getAttribute("visitTimes");				response.getWriter().println(times);	}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		doGet(request, response);	}}

  

注:我是初学者,发表博客只是学习笔记,欢迎探讨指教,希望可以结实良师益友。

转载于:https://www.cnblogs.com/nophy/p/3791478.html

你可能感兴趣的文章
单页面应用程序(SPA)的优缺点
查看>>
http请求和http响应详细解析
查看>>
Centos 配置eth0 提示Device does not seem to be present
查看>>
OS开发入门教程(1)
查看>>
arduino 驱动电调
查看>>
一个游标的性能问题
查看>>
JMeter学习-2 JMeter环境搭建
查看>>
SQL SERVER 2012疑难问题解决方法
查看>>
关于Android RenderScript 的详细说明和一些实用文档
查看>>
POJ1051 P,MTHBGWB
查看>>
士兵队列训练问题
查看>>
js时间戳怎么转成日期格式
查看>>
div宽度设置无效问题解决
查看>>
【ArcGIS Server 开发系列】Flyingis六大系列讲座精品PDF奉献
查看>>
SQL Server 2008空间数据应用系列九:使用空间工具(Spatial Tools)导入ESRI格式地图数据...
查看>>
3大主流NoSQL数据库性能对比测试报告
查看>>
pandas.DataFrame对行和列求和及添加新行和列
查看>>
【转载】后缀自动机学习总结
查看>>
YTU 2896: J--Zipper
查看>>
jQuery 源码分析 7: sizzle
查看>>