zoukankan      html  css  js  c++  java
  • ServletContext

    ServletContext概述

    ServletContext,是一个全局的储存信息的空间,服务器开始,其就存在,服务器关闭,其才释放。request,一个用户可有多个;session,一个用户一个;而servletContext,所有用户共用一个。所以,为了节省空间,提高效率,ServletContext中,要放必须的、重要的、所有用户需要共享的线程又是安全的一些信息。

    Servlet上下文:Servlet上下文提供对应用程序中所有Servlet所共有的各种资源和功能的访问。Servlet上下文API用于设置应用程序中所有Servlet共有的信息。Servlet可能需要共享他们之间的共有信息。运行于同一服务器的Servlet有时会共享资源,如JSP页面、文件和其他Servlet。

    举例:

    如,做一个购物类的网站,要从数据库中提取物品信息,如果用session保存这些物品信息,每个用户都访问一便数据库,效率就太低了;所以要用来Servlet上下文来保存,在服务器开始时,就访问数据库,将物品信息存入Servlet上下文中,这样,每个用户只用从上下文中读入物品信息就行了。

    获取ServletContext

    ServletContext对象内部封装是该web应用的信息,一个项目只有一个ServletContext对象!可以理解成一个web应用。

      ServletConfig#getServletContext();

      GenericServlet#getServletContext();

      HttpSession#getServletContext()

      ServletContextEvent#getServletContext()

    一个web应用有多个servlet对象

    ServletContext对象的生命周期

                  创建:服务器启动

                  销毁:服务器关闭

                  域的作用范围:整个web应用

    1.怎样获得ServletContext对象

    1)ServletContext servletContext = config.getServletContext();

    2)ServletContext servletContext = this.getServletContext();

    ServletContext的作用

    (1)获得web应用全局的初始化参数

    web.xml中配置初始化参数

    通过context对象获得参数

    (2)获得web应用中任何资源的绝对路径

    方法:String path = context.getRealPath(相对于该web应用的相对地址);

    写一个相对,得到一个绝对的path

    (3)ServletContext是一个域对象

    存储数据的区域就是域对象

    ServletContext域对象的作用范围:整个web应(所有的web资源都可以随意向 servletcontext域中存取数据,数据可以共享)

    域对象的通用的方法:

    setAtrribute(String name,Object obj);

    getAttribute(String name);

    removeAttribute(String name);

  • 相关阅读:
    火狐浏览器清理缓存快捷键
    SVN使用教程总结
    如何登陆服务器
    get、put、post、delete含义与区别
    zookeeper 半数可用/选举机制
    zookeeper 分布式安装/配置/启动
    lucene 统计单词次数(词频tf)并进行排序
    selenium 爬取空间说说
    MapReduce自定义InputFormat,RecordReader
    reduce 阶段遍历对象添加到ArrayList中的问题
  • 原文地址:https://www.cnblogs.com/qq1312583369/p/11138423.html
Copyright © 2011-2022 走看看