栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ServletContext对象

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ServletContext对象

ServletContext对象简介

一、什么是ServletContext

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

二、什么是域对象?
域对象,是可以像Map一样存取数据的对象,叫域对象。
这里的域指的是存取数据的操作范围,整个web工程。
存数据 取数据 删除数据
Map put() get() remove()
域对象 setAttribute() getAttribute() removeAttribute();

ServletContext实例

所有Servlet程序都可以在ServletContext中存取数据,都可以操作ServletContext,因为一个web工程中只有一个ServletContext对象

package com.ftn.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class ContextServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        1、获取web.xml中配置的上下文参数context param
        ServletContext context = getServletConfig().getServletContext();

        String username = context.getInitParameter("username");
        String password = context.getInitParameter("password");
        System.out.println("context-param参数username的值是" + username);
        System.out.println("context-param参数password的值是" + password);

//        2、获取当前的工程路径,格式: /工程路径
        System.out.println("当前工程路径:" + context.getContextPath());
//        3、获取工程部署后在服务器硬盘上的绝对路径
        //斜杠被服务器解析地址为:http://ip:port/工程名/
        System.out.println("工程部署的路径:" + context.getRealPath("/"));
//        4、像Map一样存取数据
        System.out.println(context.getAttribute("key1"));
        //存数据
        context.setAttribute("key1","value1");
        //取数据
        System.out.println(context.getAttribute("key1"));
        //打印地址
        System.out.println(context);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
11

context-param标签中的内容属于整个web工程,所有Servlet程序都可以使用


    
        username
        root
    
    
        password
        123456
    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/459356.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号