黑马程序员技术交流社区
标题:
ServletConfig与ServletContext区别与联系
[打印本页]
作者:
许玉飞嵩
时间:
2015-10-21 17:35
标题:
ServletConfig与ServletContext区别与联系
前段
时间
我把
ServletConfig与ServletContext梳理了一下,你是不是也有好多疑问呢?欢迎批评指正
在MyServlet(自定义的Servlet)的基类
GenericServlet
中,
接口ServletConfig
的实例是作为其成员变量来参与运作的,它被放到了
GenericServlet中
,
表明了它局限于某个具体的MyServlet中 ,相对于整个web项目来说,它是局部变量。源码为:
private transient ServletConfig config;
public ServletConfig getServletConfig()
{
return config;
}
而
接口ServletContext
的实例是通过
抽象类GenericServlet
中的方法获得的,具体方法如下:
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}
而
getServletContext()
又是在GenericServlet的实现类
StandardWrapperFacade
中实现的,具体代码如下:
public ServletContext getServletContext() {
if (context == null) {
context = config.getServletContext();
if ((context != null) && (context instanceof ApplicationContext))
context = ((ApplicationContext) context).getFacade();
}
return (context);
}
其中
类
ApplicationContext
是整个web项目的全局变量,上面的函数
getServletContext()
把
ServletContext实例
强转为
ApplicationContext实例,也即
全局变量。
综上所述,接口ServletConfig的实例是web项目的局部变量,而接口ServletContext的实例是web项目的全局共享变量
知道他们定义之后有什么用呢?然并卵……我们还需要它们怎么用。ServletConfig顾名思义,是Servlet的配置文件类,谈到配置文件,那我们必须说说web.xml了,当你在网站上点击一个链接时,你的客户端(也就是你的web浏览器)会发送一个请求给web服务器(你暂时可以狭义的理解为你的tomcat),紧接着web服务器会去你的项目部署文件
web.xml
中去寻找访问的资源,ServletConfig和ServletContext就可以在这里使用,他们在这里的作用是你的web项目加载时的一些初始化配置,如你想项目加载时就把你的用户名和密码配置在你的LoginServlet中,以便做静态登录(非数据库登录),这时候你就可以在
web.xml
里这样写
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>前世埋你张公子</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>I love Zhang childe</param-value>
</init-param>
</servlet>
这时候你就可以在你的LoginServlet里的doGet方法或者doPost方法中获得上述配置信息了。具体获得方法如下:
ServletConfig config = this.getServletConfig();
String username = config.getInitParameter("name");
String password = config.getInitParameter("password");
或者
String username = this.getInitParameter("name");
String password = this.getInitParameter("password");
此时的配置只在你的LoginServlet里可用,如果你在其他Servlet也需要用一下配置信息怎么办,如数据库的驱动、用户名和密码等信息,那时候你就需要在
web.xml
里配置全局配置信息了,注意了,上面配置的信息是
<servlet>
标签下的子目录,而全局的是在根目录
<web-app>
标签下的,具体代码如下:
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
这时候你就可以在你项目里任何一个Servlet里的doGet方法或者doPost方法中获得上述配置信息了。具体获得方法如下:
ServletContext context = this.getServletContext();
String driver = context.getInitParameter("driver");
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2