• 一文带你了解ServletContext


    1.ServletContext是啥

    ServletContext是一个全局的储存信息的空间,服务器开始就存在,服务器关闭才释放

    架构图示:

    在这里插入图片描述

    我们可以把ServletContext当成一个公用的空间,可以被所有的客户访问,WEB容器在启动时,它会为每个Web应用程序都创建一个对应的ServletContext,它代表当前Web应用,并且它被所有客户端共享,公共聊天室就会用到它

    同时,多个Servlet也可以通过ServletContext来进行通信操作

    当web应用关闭、Tomcat关闭或者Web应用reload的时候,ServletContext对象会被销毁🐢


    2.最简单的demo

    首先我们编写一个Servlet用于向公共空间设置键值对信息:

    public class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext servletContext = this.getServletContext();
            String say = "Hello!";
            servletContext.setAttribute("say", say);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    再编写一个Servlet用于读取公共空间中的信息:

    public class GetSomething extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletContext servletContext = this.getServletContext();
            String say = (String) servletContext.getAttribute("say");
            response.getWriter().println(say);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    这样就通过ServletContext实现了一个最基本的Servlet通信了!


    3.ServletContext 应用实例之获取初始化参数

    假设我们的web.xml中存在下面的参数内容:

    <context-param>
        <param-name>urlparam-name>
        <param-value>jdbc:mysql://localhost:3306/mybatisparam-value>
    context-param>
    
    • 1
    • 2
    • 3
    • 4

    可以通过Servlet - getInitParameter获取初始化配置信息:

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        String url = servletContext.getInitParameter("url");
        response.getWriter().println(url);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    简析低功耗蓝牙芯片PHY6222/PHY6252 蓝牙锁的应用
    CEX暴雷怎么办 一文读懂加密钱包产业现状
    裸机程序--时间片调度
    分布式系统常见理论讲解
    数据中台建设模式的4大趋势和3大重点总结全了
    跑分平台的运作模式、业务流程及风险防控
    elasticsearch wildcard 慢查询原因分析(深入到源码!!!)
    useReducer
    内存管理总结
    curl命令行发送post/get请求
  • 原文地址:https://blog.csdn.net/Gherbirthday0916/article/details/127570529