0
点赞
收藏
分享

微信扫一扫

ServletContext功能 域对象

看山远兮 2022-03-16 阅读 49

与对象: 共享数据

创建两个Servlet类, 一个是ServletContextDemo3 和ServletContextDemo4, 在ServletContextDemo3设置数据, 在ServletContextDemo4获取数据

代码展示
ServletContextDemo3

@WebServlet("/servletContextDemo3")
public class ServletContextDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取httpServlet对象
        ServletContext context = this.getServletContext();

        //设置数据
        context.setAttribute("msg","haha");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

ServletContextDemo4

@WebServlet("/servletContextDemo4")
public class ServletContextDemo4 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取httpServlet对象
        ServletContext context = this.getServletContext();

        //获取数据
        Object msg = context.getAttribute("msg");

        System.out.println(msg);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}


启动服务器,运行ServletContextDemo3 , 再在另一个浏览器上运行ServletContextDemo4
在这里插入图片描述

举报

相关推荐

0 条评论