ServletContextDemo

1、servlet 之间共享数据

 

package xw.servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 演示向Servletcontext中保存数据
 *
 */
public class AServletContext extends HttpServlet {

    /*
     * 1. 获取ServletContext对象
     * 2. 调用其setAttribute()方法完成保存数据
     */    
    
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        ServletContext servletContext=this.getServletContext(); 
        servletContext.setAttribute("name","zhangsan");        
    }    
}

 

 

package xw.servlet;

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;
/**
 * 演示从ServletContext中获取数据
 */
public class BServletContext extends HttpServlet {
    /*
     * 1. 获取ServletContext对象
     * 2. 调用其getAttribute()方法完成获取数据
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext servletContext=this.getServletContext();
        System.out.println(servletContext.getAttribute("name"));         
    }
}

 

先运行AServletContext  再运行 BServletContext

 

2、ServletContext 统计页面访问量

 

 

package xw.servlet;

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 CServletContext extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        /*
         * 1. 获取ServletContext对象
         * 2. 从ServletContext对象中获取名为count的属性
         *   3. 如果存在:给访问量加1,然后再保存回去;
         *   4. 如果不存在:说明是第一次访问,向Servletcontext中保存名为count的属性,值为1
         */
        ServletContext app = this.getServletContext();
        Integer count = (Integer)app.getAttribute("count");
        if(count == null) {
            app.setAttribute("count", 1);
        } else {
            app.setAttribute("count", count+1);
        }
        
        /*
         * 向浏览器输出
         *   需要使用响应对象!
         */
        PrintWriter pw = response.getWriter();
        pw.print("<h1>" + count + "</h1>");
    }

}

 

 

 

访问路径,显示效果如下:

posted on 2015-11-02 15:49  weiqinshian  阅读(187)  评论(0编辑  收藏  举报