ServletContext的使用

ServletContext的对象由Web容器在部署项目时创建。该对象可用于从web.xml文件获取配置信息。每个Web应用程序只有一个ServletContext对象。

如果所有Servlet都需要用到这个参数,则最好使用<context-param>元素在web.xml文件定义该参数。因为<context-param>参数是全局的。

1 ServletContext的好处

如果一些数据需要共享给所有Servlet使用,希望易于维护,那么最好将它们在web.xml文件中使用<context-param>来定义。而<context-param>的参数只能被ServletContext对象读取。这样的好处是,<context-param>参数如果更改了,则无需修改Servlet,维护起来方便许多。

2 ServletContext接口的应用场景

ServletContext对象的用法很多。下面是其中一些用法:

  1. ServletContext的对象提供了容器和Servlet之间的接口。
  2. ServletContext对象可用于从web.xml文件获取配置信息。
  3. ServletContext对象可用于设置,获取或删除web.xml文件中的属性。
  4. ServletContext对象可用于提供应用程序间的通信。

3 ServletContext的常用方法

下面列出了ServletContext接口的一些常用方法。

  1. public String getInitParameter(String name):返回指定参数名称的参数值。
  2. public Enumeration getInitParameterNames():返回上下文的初始化参数的名称。
  3. public void setAttribute(String name,Object object):在Web应用程序范围内设置给定的对象。
  4. public Object getAttribute(String name):返回指定名称的属性。
  5. public Enumeration getInitParameterNames():以字符串对象的枚举形式返回上下文的初始化参数的名称。
  6. public void removeAttribute(String name):从ServletContext中删除具有给定名称的属性。

4 获取ServletContext对象

  1. ServletConfig接口的getServletContext()方法返回ServletContext的对象。
  2. GenericServlet类的getServletContext()方法返回ServletContext的对象。
//我们可以从ServletConfig对象中获取ServletContext对象  
ServletContext application = getServletConfig().getServletContext();
  
//获取ServletContext对象的另一种便捷方法  
ServletContext application = getServletContext(); 

5 定义context-param参数语法

web-app的<context-param>标签用于在Web应用程序范围内定义初始化参数。param-name和param-value是<context-param>的子元素。param-name元素定义参数名称,而param-value定义其值。

<web-app>  
 ......  
      
  <context-param>  
    <param-name>parametername</param-name>  
    <param-value>parametervalue</param-value>  
  </context-param>  
 ......  
</web-app>  

6 读取指定参数的案例

6.1 编写DemoServlet

import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class DemoServlet extends HttpServlet{

    public void doGet(HttpServletRequest req,HttpServletResponse res)
            throws ServletException,IOException
    {
        res.setContentType("text/html;charset=utf-8");
        PrintWriter pw=res.getWriter();

        //创建ServletContext对象
        ServletContext context=getServletContext();

        //获取指定的Web上下文参数,并打印输出
        String driverName=context.getInitParameter("dname");
        pw.println("驱动名称是="+driverName);

        pw.close();
    }

}

6.2 配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--定义Web应用上下文参数-->
    <context-param>
        <param-name>dname</param-name>
        <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
    </context-param>
    
    <servlet>
        <servlet-name>DemoServlet</servlet-name>
        <servlet-class>DemoServlet</servlet-class>
    </servlet>
   <servlet-mapping>
       <servlet-name>DemoServlet</servlet-name>
       <url-pattern>/demo</url-pattern>
   </servlet-mapping>
    

</web-app>

6.3 运行测试

访问:http://localhost:8080/demo,效果如下:

7 读取所有参数的案例

7.1 编写DemoServlet

import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class DemoServlet extends HttpServlet{

    public void doGet(HttpServletRequest req,HttpServletResponse res)
            throws ServletException,IOException
    {
        res.setContentType("text/html;charset=utf-8");
        PrintWriter out=res.getWriter();

        ServletContext context=getServletContext();
        Enumeration<String> e=context.getInitParameterNames();

        String str="";
        while(e.hasMoreElements()){
            str=e.nextElement();
            out.print("<br> "+context.getInitParameter(str));
        }
    }

}

7.2 配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <!--定义多个Web应用上下文参数-->
    <context-param>
        <param-name>dname</param-name>
        <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
    </context-param>

    <context-param>
        <param-name>username</param-name>
        <param-value>system</param-value>
    </context-param>

    <context-param>
        <param-name>password</param-name>
        <param-value>oracle</param-value>
    </context-param>


    <servlet>
        <servlet-name>DemoServlet</servlet-name>
        <servlet-class>DemoServlet</servlet-class>
    </servlet>
   <servlet-mapping>
       <servlet-name>DemoServlet</servlet-name>
       <url-pattern>/demo</url-pattern>
   </servlet-mapping>
    

</web-app>

7.3 运行测试

访问:http://localhost:8080/demo,效果如下:

热门文章

优秀文章