1、ServletContext代表着整个JavaWeb应用,每个项目只有唯一的ServletContext的实例。
2、生命周期
服务器启动时创建
服务器关闭时销毁
3、获取ServletContext对象
方式1:通过ServletConfig来获取ServeltContext
//获取ServletContext的引用 public class ServletDemo1 extends HttpServlet { private ServletConfig config; public void init(ServletConfig config) throws ServletException { this.config = config; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = config.getServletContext(); sc.setAttribute("p", "abc"); //获取全局参数 System.out.println(sc.getInitParameter("encoding")); System.out.println("Demo1:"+sc); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
方式2:直接获取,推荐
public class ServletDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServletContext ServletContext sc = getServletContext(); Object value = sc.getAttribute("p"); //获取全局参数 System.out.println(sc.getInitParameter("encoding")); System.out.println(">>>>>>>:"+value); System.out.println("Demo2:"+sc); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
4、ServletContext应用
、实现多个Servlet之间的数据共享,ServletContext叫做一个域(范围)对象
时间: 2024-10-13 17:30:52