Servlet 之 ServletContext类

什么是ServletContext

  1. ServletContext是一个接口。
  2. 表示servlet程序的上下文对象。
  3. 一个web工程只有一个 ServletContext对象实例。
  4. 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 {

    }
}

测试结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值