什么是ServletContext
- ServletContext是一个接口。
- 表示servlet程序的上下文对象。
- 一个web工程只有一个 ServletContext对象实例。
- ServletContext对象在web工程部署启动时创建,web工程停止即销毁。
ServletContext类的四个作用
1.获取web.xml中配置的上下文参数。
2.获取当前的工程路径。 格式为:/工程路径
3.获取工程部署后在服务器硬盘上的绝对路径。
4.以Map的形式存储数据。
在web.xml中的配置信息如下
<!--context-param是上下文参数(贯穿整个web工程)-->
<context-param>
<param-name>username</param-name>
<param-value>context</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>66666</param-value>
</context-param>
<servlet>
<servlet-name>Servlet_Context</servlet-name>
<servlet-class>com.servlet.Servlet_Context</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet_Context</servlet-name>
<url-pattern>/servlet_context</url-pattern>
</servlet-mapping>
注意:context-param参数的配置不包含在servlet参数里
测试代码如下
package com.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class Servlet_Context extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取web.xml中配置的上下文参数context-param
ServletContext servletContext = getServletContext();
String username = servletContext.getInitParameter("username");
String password = servletContext.getInitParameter("password");
System.out.println("context-param参数所配置的username值为:" + username);
System.out.println("context-param参数所配置的password值为:" + password);
//获取当前工作路径
System.out.println("当前的工作路径为:" + getServletContext().getContextPath());
//获取工程部署后在服务器上的绝对路径
//此处的斜杠被服务器解析为:http://ip:port/工程名/
System.out.println("工程部署的绝对路径是:" + servletContext.getRealPath("/"));
System.out.println("工程下css的绝对路径是:" + servletContext.getRealPath("/css"));
//以Map形式存取数据
servletContext.setAttribute("key1","value1");//将数据存入数据域
System.out.println("key1的值为:" + servletContext.getAttribute("key1"));//从数据域中取出数
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}