ServletContext的对象由Web容器在部署项目时创建。 该对象可用于从web.xml文件获取配置信息。 每个Web应用程序只有一个ServletContext对象。
如果有信息要共享给多个servlet使用,最好在web.xml文件中使用元素提供它。
如果有任何信息要共享给所有的servlet使用,并且要让它容易维护,最好的办法就是在web.xml文件中提供这些信息,所以如果信息要更改直接在web.xml中修改,而不需要修改servlet代码。
ServletContext接口的使用
有很多ServletContext对象可以使用。 其中一些如下:
web.xml文件获取配置信息。web.xml文件中属性。ServletContext接口方法给出了一些常用的ServletContext接口方法。
| 序号 | 方法 | 描述 |
|---|---|---|
| 1 | public String getInitParameter(String name) | 返回指定参数名称的参数值。 |
| 2 | public Enumeration getInitParameterNames() | 返回上下文的初始化参数的名称。 |
| 3 | public void setAttribute(String name,Object object) | 在应用程序范围内设置给定的对象。 |
| 4 | public Object getAttribute(String name) | 返回指定名称的属性。 |
| 5 | public Enumeration getInitParameterNames() | 返回上下文的初始化参数的名称,作为String对象的枚举。 |
| 6 | public void removeAttribute(String name) | 从servlet上下文中删除给定名称的属性。 |
ServletContext接口的对象?ServletConfig接口的getServletContext()方法返回ServletContext对象。GenericServlet类的getServletContext()方法返回ServletContext对象。getServletContext()方法的语法public ServletContext getServletContext()
getServletContext()方法的示例ServletContext application=getServletConfig().getServletContext();
ServletContext application=getServletContext();
Context范围内提供初始化参数的语法Web应用程序的context-param元素的子元素用于定义应用程序范围中的初始化参数。 参数名称和参数值是context-param的子元素。param-name元素定义参数名称,param-value定义其值。参考以下配置代码片段 -
<web-app>
......
<context-param>
<param-name>parameter_nameparam-name>
<param-value>parameter_valueparam-value>
context-param>
......
web-app>
ServletContext示例ContextServlet.java
public class ContextServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 设置服务器内容类型
response.setContentType("text/html");
// 获取服务器的输出对象
PrintWriter out = response.getWriter();
// 获取ServletContext对象
ServletContext context = getServletContext();
String driverName = context.getInitParameter("dname");
out.println("driver name is "+driverName+"");
out.close();
}
}
Context.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ContextServlettitle>
head>
<body>
<div style="text-align: center">
请<a href="context">点击这里a>查看Context信息
div>
body>
html>
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>ContextServletdisplay-name>
<welcome-file-list>
<welcome-file>Context.htmlwelcome-file>
welcome-file-list>
<servlet>
<servlet-name>ContextServletservlet-name>
<servlet-class>ContextServletservlet-class>
servlet>
<context-param>
<param-name>dnameparam-name>
<param-value>com.mysql.jdbc.Driverparam-value>
context-param>
<servlet-mapping>
<servlet-name>ContextServletservlet-name>
<url-pattern>/contexturl-pattern>
servlet-mapping>
we-app>