Servlet笔记——(2.4) ServletContext(重要)
来源:互联网 发布:淘宝寄到日本 编辑:程序博客网 时间:2024/06/07 14:04
服务器会为每个应用创建一个ServletContext对象,该对象被包含在ServletConfig对象中。ServletContext对象的创建是在服务器启动时完成的;销毁是在服务器关闭时完成的。
ServletContext对象的作用是在整个Web应用的动态资源之间共享数据。例如在AServlet中向ServletContext对象中保存一个值,然后在BServlet中就可以获取整个值,这就是共享数据了。
接口ServletContext的定义可参考“JSP内置对象之 application”对象,“application”对象的原型即实现了该接口。
2.4.1 获取ServletContext实例
(1) 在void init(ServletConfig config)中:ServletContext context = config.getServletContext();ServletConfig接口的getServletContext()方法可以用来获取ServletContext对象。
(2) GenericServlet类继承并重写了getServletContext()方法,所以可以直接使用this.getServletContext()来获取。
(1) ServletConifg#getServletContext()
(2) GenericServlet#getServletContext()
(3) HttpSession#getServletContext()
(4) ServletContextEvent#getServletContext()
具体代码如下:
public class AServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/* * 1.获取ServletContext对象 * 2.验证ServletContext对象只有一份 * */// AServlet - HttpServlet - GenericServlet - Servlet + ServletConfig//ServletConfig config = this.getServletConfig();//ServletContext context = config.getServletContext();ServletContext application = this.getServletContext();System.out.println("AServlet: " + application);}
public class DServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("DServlet: " + this.getServletContext());}
分别访问AServlet和DServlet,观察结果,得到的ServletContext是同一个对象:
org.apache.catalina.core.ApplicationContextFacade@2ab44e2d
org.apache.catalina.core.ApplicationContextFacade@2ab44e2d
- Servlet笔记——(2.4) ServletContext(重要)
- Servlet笔记——(2.4.5)ServletContext获取访问量编程练习
- JavaWeb三大组件之一Servlet【ServletContext(重要)】
- ServletContext(重要)
- 笔记之servlet的ServletContext对象(ServletContext的应用)
- Servlet学习笔记—ServletContext对象
- Servlet学习笔记—ServletContext的详解
- Servlet——ServletContext
- Servlet—ServletConfig、ServletContext
- Servlet学习笔记(五):ServletConfig和ServletContext详解
- Servlet——ServletContext 对象
- Servlet——ServletContext 对象
- Servlet分析(4)ServletContext
- ---servlet(二)ServletConfig,ServletContext
- servlet学习笔记---servletContext
- Servlet 笔记( 二 ServletContext)
- 20160410servlet学习笔记servletContext
- Servlet和ServletContext相关笔记
- 常见的各种异常
- 对Dicom数据的一点理解
- 遗传算法深入学习上
- 500Keyboard Row
- spring 整合 activemq
- Servlet笔记——(2.4) ServletContext(重要)
- iOS开发 TableView的headerInSectionView 不悬浮
- 配置Tomcat使用https协议
- C#.NET MVC 导出WORD文档
- 导入图片的几种方式
- python学习第二天
- 微信小程序对接服装行业
- CUDA 9.0在Ubuntu上的安装
- java常用颜色属性