一、ServletContext的生命周期
生:服务器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。销毁:服务器关闭或者当前应用删除。
二、ServletContext对象的创建:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到ServletContext的方式1:通过ServletConfig对象的getServletContext()的方法 ServletContext context=this.getServletConfig().getServletContext(); //得到ServletContext的方式2 context=this.getServletContext(); }
三、ServletContext的作用
1.多个Servlet通过ServletContext对象实现数据共享。
由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。
2.获取WEB应用的初始化参数,类似于ServletConfig。
<context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/ordername</param-value> </context-param>
3、实现Servlet的转发:
//Servlet的转发 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String date="ServletContext"; //不能通过context,要通过request域 this.getServletContext().setAttribute("date", date); RequestDispatcher rd=this.getServletContext().getRequestDispatcher("/demo.jsp"); rd.forward(request, response); }
转发给 demo.jsp
<body> <h1> <font color="red"> <% String date=(String)application.getAttribute("date"); out.write(date); %> </font> </h1> </body>
4.利用ServletContext对象读取资源文件。
原文:http://www.cnblogs.com/lyjs/p/4869930.html