<7>ServletContext 类

1.ServletContext 类简介

  • 1、ServletContext 是一个接口,它表示 Servlet 上下文对象
  • 2、一个 web 工程,只有一个 ServletContext 对象实例。
  • 3、ServletContext 对象是一个域对象。
  • 4、ServletContext 是在 web 工程部署启动的时候创建。在 web 工程停止的时候销毁。

注:
域对象,是可以像 Map 一样存取数据的对象,叫域对象。
这里的域指的是存取数据的操作范围,整个 web 工程。
在这里插入图片描述

2.ServletContext 类的四个作用

  • 1、获取 web.xml 中配置的上下文参数 context-param
  • 2、获取当前的工程路径,格式: /工程路径
  • 3、获取工程部署后在服务器硬盘上的绝对路径
  • 4、像 Map 一样存取数据

2.1 获取XML配置的上下文参数、文件工程路径、绝对路径

例如Servlet在XML中的配置为:

<!--context-param 是上下文参数(它属于整个 web 工程)-->
    <context-param>
        <param-name>username</param-name> 
        <param-value>abc</param-value>
    </context-param>

Servlet 中的代码:

public class HelloServlet03 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = getServletConfig().getServletContext();
        // 1、获取 web.xml 中配置的上下文参数 context-param
        String username = context.getInitParameter("username");
        System.out.println("context-param 参数 username 的值是:" + username);

        // 2、获取当前的工程路径,格式: /工程路径
        System.out.println( "当前工程路径:" + context.getContextPath() );

        // 3、获取工程部署后在服务器硬盘上的绝对路径
        System.out.println("工程部署的路径是:" + context.getRealPath("/"));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

在这里插入图片描述

2.2 像 Map 一样存取数据

Servlet 中的代码:

public class HelloServlet03 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = getServletConfig().getServletContext();
        // 1、获取 web.xml 中配置的上下文参数 context-param
        String username = context.getInitParameter("username");
        System.out.println("更改前的username:" + username);
		//2、设置 web.xml 中配置的上下文参数 context-param
        context.setAttribute("username", "edf");
        System.out.println("更改后的username:" + context.getAttribute("username"));

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

实验结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值