Servlet之ServletConfig与ServletContext的相关使用(二)

作者:叁念


一、ServletConfig

1.1 ServletConfig有何作用

  • 在Servlet的配置文件Web.xml中,可以使用标签为servlet配置一些初始化参数。
  • web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。所以通过ServletConfig对象就可以得到当前servlet的初始化参数信息。

1.2 ServletConfig实例

1.编写配置文件web.xml,使用使用init-param标签配置初始化参数


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Demodisplay-name>
    <welcome-file-list>
        <welcome-file>index.htmlwelcome-file>
        <welcome-file>index.htmwelcome-file>
        <welcome-file>index.jspwelcome-file>
        <welcome-file>default.htmlwelcome-file>
        <welcome-file>default.htmwelcome-file>
        <welcome-file>default.jspwelcome-file>
    welcome-file-list>
    <servlet>
        <servlet-name>MyServletservlet-name>
        <servlet-class>com.cn.MyServletservlet-class>
        
        <init-param>
            <param-name>charsetparam-name>
            <param-value>UTF-8param-value>
        init-param>
        
        <init-param>
            <param-name>nameparam-name>
            <param-value>sannianparam-value>
        init-param>
        
        <init-param>
            <param-name>passwordparam-name>
            <param-value>123param-value>
        init-param>
    servlet>

    <servlet-mapping>
        <servlet-name>MyServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

2.创建servlet,取出初始化参数

package com.cn;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取ServletConfig对象
        ServletConfig config = this.getServletConfig();
        // 取出初始化信息
        System.out.println(config.getServletName());
        System.out.println(config.getInitParameter("name"));
        Enumeration enumeration = config.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String nextElement = enumeration.nextElement();
            String parameter = config.getInitParameter(nextElement);
            System.out.println(parameter);
        }
    }
}

访问:http://localhost:8080/项目名/
效果如下:

Servlet之ServletConfig与ServletContext的相关使用(二)_第1张图片

3.总结作用

  • 获取自定义配置参数信息
  • 获得字符集参数编码信息
  • 获得数据库连接参数信息
  • ……….

二、ServletContext

2.1 ServletContext介绍

1.概念

  • 代表的是一个web的应用环境(上下文):
    WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
  • 内部封装的是该web应用的信息:
    ServletContext对象被包含在ServletConfig对象中,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得对ServletContext对象的引用。
  • ServletContext对象一个web应用就只有一个:
    由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。

2.生命周期

  • 创建:该web应用被加载时
  • 销毁:web应用被卸载时

2.2 ServletContext实例

1.获取初始化参数,同ServletConfig

编写web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Demodisplay-name>
    <welcome-file-list>
        <welcome-file>index.htmlwelcome-file>
        <welcome-file>index.htmwelcome-file>
        <welcome-file>index.jspwelcome-file>
        <welcome-file>default.htmlwelcome-file>
        <welcome-file>default.htmwelcome-file>
        <welcome-file>default.jspwelcome-file>
    welcome-file-list>
    
    <context-param>
        <param-name>cpparam-name>
        <param-value>this is valueparam-value>
    context-param>
  web-app>

书写Servlet

package com.cn;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String parameter = context.getInitParameter("cp");
        System.out.println(parameter);
    }
}

效果如下

Servlet之ServletConfig与ServletContext的相关使用(二)_第2张图片

2.获得web应用中任意资源的绝对路径(最重要)

// String path = context.getRealPath(相对于web应用的相对路径)
String realPath = this.getServletConfig().getServletContext().getRealPath("/");
System.out.println(realPath);
//打印如下 D:\codingsoft\tomcat\wtpwebapps\Demo\

3.ServletContext是一个域对象(非常重要),可以在多个Servlet通过ServletContext对象实现数据共享

  • 什么是域对象呢?———— 存储数据的区域就是域对象
  • 域对象通用的方法
    setAttribute(String name, Object value); ———— 设置一个键值对
    getAttribute(String name) ———— 获取一个值
    removeAttribute(String name) ———— 移除一个键值对

创建ServletContextDemo设置属性值

package com.cn;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ServletContextDemo")
public class ServletContextDemo extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.getServletContext().setAttribute("binggo", "666");
    }
}

创建ServletContextDemo1获取属性值

package com.cn;

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

@WebServlet("/ServletContextDemo1")
public class ServletContextDemo1 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Object attribute = this.getServletContext().getAttribute("binggo");
        System.out.println(attribute.toString());
    }
}

访问方式:顺序,先存后取,否则会空指针异常
http://localhost:8080/Demo/ServletContextDemo
http://localhost:8080/Demo/ServletContextDemo1

效果:打印 666

注意:ServletContext域的作用范围:整个web应用

4.实现转发

package com.cn;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ServletContextDemo2")
public class ServletContextDemo2 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/MyServlet");
        dispatcher.forward(request, response);
    }
}

源码:
链接: https://pan.baidu.com/s/1Y-9f_OytfC5Q0G8RtA8LnQ 密码: gc7y

你可能感兴趣的:(Servlet)