码迷,mamicode.com
首页 > Web开发 > 详细

Servlet学习的两个案例之网站访问次数的统计

时间:2014-06-18 14:37:11      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:class   blog   java   http   ext   com   

一、统计次数的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);
	}

}

  

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

Servlet学习的两个案例之网站访问次数的统计,布布扣,bubuko.com

Servlet学习的两个案例之网站访问次数的统计

标签:class   blog   java   http   ext   com   

原文地址:http://www.cnblogs.com/nophy/p/3791478.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!