与对象: 共享数据
创建两个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