码迷,mamicode.com
首页 > 其他好文 > 详细

ServlertContext

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

标签:extend   启动   code   request   共享   obj   oge   java   http   

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

标签:extend   启动   code   request   共享   obj   oge   java   http   

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

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