ServletContext对象
一、引入
ServletContext对象 ,叫做Servlet的上下文对象。表示一个当前的web应用环境。当前web应用的web.xml配置文件都会存储在一个ServletContext对象中,所以一个web应用中只有一个ServletContext对象。
二、对象创建和得到
1、创建时机:加载web应用时创建ServletContext对象。
2、得到对象: 从ServletConfig对象的getServletContext方法得到。
3、模拟
1)我们设计:
创建ServletConfig对象,但这样就会多了一个参数
public void init( ServletConfig config,ServletContext context ){
得到ServletConfig对象
得到ServletContext对象;
}
2)sun公司设计:
1)//创建ServletContext对象,ServletContext对象肯定早于ServletConfig对象被创建,因为ServletContext是在加载web配置文件时创建,而ServletConfig则是在创建Servlet对象之后创建的。
ServletContext context = new ServletContext()
2)//创建ServletConfig对象
class ServletConfig{
ServletContext context;
public ServletContext getServletContxt(){
return contxt;
}
}
ServetConfig config = new ServletConfig();
//ServletContext是ServletConfig中的一个成员变量,所以会定义get,set方法
config.setServletContxt(context);
public void init( ServletConfig config ){
得到ServletConfig对象
从ServletConfig对象中得到ServletContext对象
SerlvetContext context = config.getServletContext();
}
三、ServletContext对象的核心API(作用)
1、java.lang.String getContextPath() –得到当前web应用的路径
方式二获取ServletContext对象详解,查看GenericServlet源码:
2、java.lang.String getInitParameter(java.lang.String name) –得到web应用的初始化参数
3、java.util.Enumeration getInitParameterNames()
web应用参数可以让当前web应用的所有servlet获取,servlet的参数只能由当前的这个sevlet获取!
四、Servlet重命名问题
1、修改了Servlet的名称,但是tomcat下的webapp目录下的web应用名称却并没有更改,web.xml文件也引用不了,就会出错。
2、完整修改Servlet项目名称:
1)项目右键——>Refactor——>Rename
2)项目右键——>properties——>web——>修改