一個Web應用中的所有Servlet,共用同一個ServletContext對象
因此,ServletContext對象的域屬性,可以被該Web應用中的所用Servlet訪問
在ServletContext介面中,定義了分別用於增加、刪除、設定ServletContext域屬性的4個方法
ServletContext介面的方法 Enumeration getAttributeNames()
返回一個Enumeration對象,該對象包含所有存放在ServletContext中的所有域屬性名稱 Object getAttribute(String name)
根據參數指定的屬性名稱,返回一個與之匹配的域屬性值 Void removeAttribute(String name)
根據參數指定的域屬性名稱,從ServletContext中刪除匹配的域屬性 Void setAttribute(String name,Object obj)
設定ServletContext的域屬性,name是域屬性名稱,obj是域屬性值
執行個體程式
編寫TestServlet04類
package cn.itcast.chapter04.servlet;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class TestServlet04 extends HttpServlet{public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{ServletContext context=this.getServletContext();//通過setAttribute()方法設定屬性值context.setAttribute("data","this servlet save data");}public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{this.doGet(request,response);}}
setAttribute()方法,用於設定ServletContext對象的屬性值
編寫TestServlet05類
package cn.itcast.chapter04.servlet;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class TestServlet05 extends HttpServlet{public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{PrintWriter out=response.getWriter();ServletContext context=this.getServletContext();//通過getAttribute()方法擷取屬性值String data=(String)context.getAttribute("data");out.println(data);}public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{this.doGet(request,response);}}
getAttribute()方法,用於擷取ServletContext對象的屬性值
編寫web.xml檔案
<?xml version="1.0" encoding="ISO-8859-1"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"><servlet> <servlet-name>TestServlet04</servlet-name> <servlet-class>cn.itcast.chapter04.servlet.TestServlet04</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet04</servlet-name> <url-pattern>/TestServlet04</url-pattern></servlet-mapping><servlet> <servlet-name>TestServlet05</servlet-name> <servlet-class>cn.itcast.chapter04.servlet.TestServlet05</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet05</servlet-name> <url-pattern>/TestServlet05</url-pattern></servlet-mapping></web-app>
啟動Tomcat,在瀏覽器中輸入
http://localhost:8080/chapter04/TestServlet04
訪問TestServlet04,將資料存入ServletContext對象
然後,輸入地址
http://localhost:8080/chapter04/TestServlet05
訪問TestServlet05
顯示結果如下