首页 > 技术文章 > ServletContext与ServletConfig对象详解

jueyushanlang 2017-12-02 11:40 原文

一、ServletContext对象详解

ServletContext代表当前web应用

当服务器启动,web应用加载完成后,立即创建一个ServletContext对象代表当前web应用。从此驻留在内存中唯一的代表当前web应用。直到服务器关闭或web应用移除出容器时,随着web应用的销毁而销毁。

1.获取ServletContext

servletConfig.getServletContext();
this.getServletContext();
在web.xml中的<web-app>根标签下定义<context-param>,可以给全局定义初始化参数,比如encode
在servlet中调用时,this.getServletContext().getInitParamter("encode"),得到String型的变量

2.加载资源文件:

路径难题
ServletContext.getRealPath("xxxxx");//会在传入的路径前拼接上当前web应用的硬盘路径。~另外在没有ServletContext的环境下,我们可以使用类加载器加载资源。但是要注意,类加载器加载资源时,路径要相对于平常加载类的位置进行计算。
ClassLoader.getResource().getPath();
ClassLoader.getResourceAsStream();

3.读取web应用的初始化:

我们可以在web.xml的根目录下为整个web应用配置一些初始化参数。
在<Context-param>标签下添加
可以通过ServletContext对象来读取这些整个web应用的初始化参数。
servletContext.getInitParamter();
servletContext.getInitParamterNames();

4.作为域对象使用:

域:一个对象具有了一个可以被看见的范围,那么利用这个对象身上的Map,可以在这个范围内共享数据,这样的对象叫做域对象。
javaweb中一共有四大作用域,其中ServletContext就是其中最大的一个。setAttribute(String name,Object value);
getAttribute(String name);
removeAttribute(String name);
getAttributeNames();

5.ServletContext域的范围:

在整个web应用中共享数据
生命周期:
服务器启动web应用加载ServletContext创建,直到服务器关闭或web应用移除出容器时随着web应用的销毁,ServletContext销毁。
主要的作用:
在整个web应用中共享数据。paramter -- 请求参数
initparamter -- 初始化参数
attribute -- 域属性

二、ServletConfig对象详解

在Servlet 的配置文件中,可以用一个或多个<init-param>标签为servlet配置一些初始化参数。
当servlet配置了初始化参数之后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给Servlet。
进而,程序员通过Servlet对象得到当前servlet的初始化参数信息。获取ServletConfig中初始化信息步骤:

1 . 创建私有变量:

private ServletConfig config = null;

2、重写init方法:

 this.config = config,从而获取ServletConfig对象;

3、获取<init-param>配置:

//获取初始化参数 String value1 = this.config.getInitParameter("x1");
//获得配置文档中<inti-param>标签下name对应的value String value2 = this.config.getInitParameter("x2");
//获取所有初始化参数 Enumeration e = this.config.getInitParameterNames();
while(e.hasMoreElements()){ String name = (String) e.nextElement(); String value = this.config.getInitParameter(name); System.out.println(name+"="+value); }

4、ServletConfig的作用:

获取字符集编码:String charset = this.config.getInitParameter("charset");
获得数据库连接信息:String url = this.config.getInitParameter("url");
String username = this.config.getInitParameter("username");
String password = this.config.getInitParameter("password");
获得配置文件:String configFile = this.config.getInitParameter("config");

推荐阅读