Servlet--ServletContext详解

2022-07-07 12:55:44

什么是ServletContext对象?

ServletContext代表的是一个web应用的环境(上下文)对象,ServletContext对象内部封装的是该web应用的信息。
一 个 w e b 应 用 只 有 一 个 S e r v l e t C o n t e x t 对 象 。 \color{red}{一个web应用只有一个ServletContext对象。}webServletContext

Servlet的生命周期

  • 创建:该web应用被加载(服务器启动或发布web应用(前提,服务器启动状态))
  • 销毁:web应用被卸载(服务器关闭,移除该web应用)

获得ServletContext对象

第一种:

ServletContext servletContext= config.getServletContext();

第二种(常用):

ServletContext servletContext1=this.getServletContext();

ServletContext的作用

  1. 获得web应用全局的初始化参数:
    web.xml中配置初始化参数
<!-- 配置初始化参数 --><context-param><param-name>testStr</param-name><param-value>helloWorld</param-value></context-param>

通过ServletContext获得初始化参数:

protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{//获得ServletContext对象
        ServletContext servletContext=this.getServletContext();//获得初始化参数
        String testStr= servletContext.getInitParameter("testStr");

        System.out.println(testStr);}

通过浏览器访问,控制台输出:

helloWorld
  1. 获得web应用中任何资源的绝对路径(重要):
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{//获得ServletContext对象
        ServletContext servletContext=this.getServletContext();//获的资源相对于该web的相对路径
        String realPath= servletContext.getRealPath("index.jsp");
        System.out.println(realPath);}

通过浏览器访问,控制台输出:

F:\IDEAworkspace\JavaEEDemo\out\artifacts\JavaEEDemo_war_exploded\index.jsp

ServletContext是一个域对象

域对象:
域对象是服务器在内存上创建的存储空间,用于在不同动态资源(servlet)之间传递与共享数据。

域对象通用方法:

方法描述
setAttribute(String name,Object value);向域对象中添加数据,添加时以key-value形式添加
getAttribute(String name);根据指定的key读取域对象中的数据
removeAttribure(String name);根据指定的key从域对象中删除数据
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{//获得ServletContext对象
        ServletContext servletContext=this.getServletContext();//向域对象中存入数据
        servletContext.setAttribute("str","helloWorld");//从域对象中取出数据
        String str=(String) servletContext.getAttribute("str");//从域对象中删除数据
        servletContext.removeAttribute("str");}

ServletContext存储数据的特点:
全局共享,里面的数据所有动态资源都可以写入和读取。

ServletContext获取当前工程名字

核心方法:

getServletContext().getContextPath();

示例:

protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{//获得工程名字
        String contextPath=getServletContext().getContextPath();

        System.out.println(contextPath);}

通过浏览器访问,控制台输出:

/JavaEEDemo
  • 作者:吴声子夜歌
  • 原文链接:https://blog.csdn.net/cold___play/article/details/100899275
    更新时间:2022-07-07 12:55:44