JavaWeb(3)之ServletContext的使用

JavaWeb(3)之ServletContext的使用

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:

ServletContext生命周期

创建:Servlet 容器启动的时候,会为托管的每一个 Web 应用程序,创建一个 ServletContext 对象。
销毁:从服务器移除托管,或者是关闭服务器。

初始化参数

Servlet 的初始化参数

WEB-INF/web.xml 中可以为特有的 Servlet 提前配置好一些需要的初始化参数,如下:

<!-- WEB-INF/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_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>testServlet</servlet-name>
        <servlet-class>com.zze.servlet.TestServlet</servlet-class>
        <init-param>
            <param-name>name</param-name>
            <param-value>bob</param-value>
        </init-param>
        <init-param>
            <param-name>age</param-name>
            <param-value>21</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>testServlet</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

接下来就可以从相应 Servlet 中获取:

package com.zze.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取 ServletConfig 实例
        ServletConfig servletConfig = getServletConfig();
        // 获取 Servlet 名称,这个名称指的是在 web.xml 中 servlet 节中配置的 servlet-name 节的值
        String servletName = servletConfig.getServletName();
        System.out.println(servletName);
        // 获取当前 Servlet 对应 web.xml 中 servlet 节下所有 init-param 节 下的 param-name 节中的值
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            String name = initParameterNames.nextElement();
            System.out.println(name);
            // 通过 init-param 下 param-name 的值获取对应 param-value 的值
            String initParameterValue = servletConfig.getInitParameter(name);
            System.out.println(initParameterValue);
        }
       /*
       输出结果:
       testServlet
       name
       bob
       age
       */
    }
}

全局初始化参数

WEB-INF/web.xml 中可以为配置好一些需要的初始化参数,任何一个 Servlet 都可获取到,如下:

<?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_4_0.xsd"
version="4.0">
    <context-param>
        <param-name>name</param-name>
        <param-value>rick</param-value>
    </context-param>
    <context-param>
        <param-name>age</param-name>
        <param-value>13</param-value>
    </context-param>
    <servlet>
        <servlet-name>testServlet</servlet-name>
        <servlet-class>com.zze.servlet.TestServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>testServlet</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

接下来就可以在 Servlet 中获取配置的初始化参数:

// Servlet
package com.zze.servlet;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        ServletContext servletContext = getServletContext();
        // 获取 web.xml 中 web-app 节下所有 context-param 节 下的 param-name 节中的值
        Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
        while (initParameterNames.hasMoreElements()) {
            String name = initParameterNames.nextElement();
            // 通过 context-param 下 param-name 的值获取对应 param-value 的值
            String value = servletContext.getInitParameter(name);
            System.out.println(String.format("name:%s value:%s", name, value));
        }
        /*
        name:name value:rick
        name:age value:13
        */
    }
}

注:全局初始化参数的使用和 Servlet 的初始化参数相似,只是它的值在所有 Servlet 中都可以获取到。

作用范围

ServletContext 实例其实也是一个域对象,存储在其中的数据可以被所有 Servlet 共享。看如下示例:

// com.zze.servlet.SetServlet
package com.zze.servlet;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        ServletContext servletContext = getServletContext();
        servletContext.setAttribute("data", "this data is from SetServlet");
        System.out.println("set success");
    }
}
// com.zze.servlet.GetServlet
package com.zze.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GetServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = getServletContext();
        String data = (String) servletContext.getAttribute("data");
        System.out.println(String.format("get success,data is '%s'",data));
    }
}

依次访问 SetServletGetServlet ,得到输出结果:

set success
get success,data is 'this data is from SetServlet'

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://www.zze.xyz/archives/javaweb3.html

Buy me a cup of coffee ☕.