首页 > 其他 > 详细

ServlertContext

时间:2017-04-06 13:50:09      阅读:550      评论:0      收藏:0      [点我收藏+]

1、ServletContext代表着整个JavaWeb应用,每个项目只有唯一的ServletContext的实例。

2、生命周期

  服务器启动时创建

  服务器关闭时销毁

3、获取ServletContext对象

  方式1:通过ServletConfig来获取ServeltContext

//获取ServletContext的引用
public class ServletDemo1 extends HttpServlet {
        
    private ServletConfig config;

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext sc = config.getServletContext();
        sc.setAttribute("p", "abc");
        
        //获取全局参数
        System.out.println(sc.getInitParameter("encoding"));
        
        System.out.println("Demo1:"+sc);
    }

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

}

方式2:直接获取,推荐

public class ServletDemo2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
     //获取ServletContext ServletContext sc
= getServletContext(); Object value = sc.getAttribute("p"); //获取全局参数 System.out.println(sc.getInitParameter("encoding")); System.out.println(">>>>>>>:"+value); System.out.println("Demo2:"+sc); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

 

4、ServletContext应用

  、实现多个Servlet之间的数据共享,ServletContext叫做一个域(范围)对象

 

ServlertContext

原文:http://www.cnblogs.com/flei/p/6642480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!