public class Servlet01 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
ServletContext demo1 = this.getServletContext();
demo1.setAttribute("testName", "testValue"); /// ①
System.out.println(demo1.getAttribute("testName")); // ②
}
@WebServlet("/demo2")
public class Demo2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
ServletContext demo2 = getServletContext();
System.out.println(demo2.getAttribute("testName")); //③
demo2.removeAttribute("testName");
System.out.println(demo2.getAttribute("testName")); // ④
}
}
}
解析:
执行 demo1.setAttribute("testName", "testValue"),往setAttribute,域中个添加键”testName”值为testValue,的键值对 执行System.out.println(demo2.getAttribute("testName"));往setAttribute,域中个添加键”testName”控制台为testValue, 通过setAttribute(String name,Object obj),可以往servletContext容器里面添加数据,通过getAttribute(String name)可以过去servletContext容器里面指定键对应的值,servletContext的容器范围比较大,他可以在另外一个servlet里面获取到存在servletContext容器里面的值, ServletContext在项目启动的时候会创建,
|