Java ServletContext對象用法解析
ServletContext對象:
ServletContext類似字節碼文件對象,在web創建的時候就自動生成了,并且是唯一的,跟隨著項目和服務器共存亡了。通過這個對象,我們可以向里面存數據(鍵值對),也可以通過別的Servlet來獲取這個數據;也可以根據相對(服務器)路徑繼來獲取絕對路徑。
ServletContext代表是一個web應用的環境(上下文)對象,ServletContext對象內部封裝是該web應用的信息,ServletContext對象一個web應用只有一個。 一個web應用有幾個servlet對象?----多個
ServletContext對象的生命周期?
創建:該web應用被加載(服務器啟動或發布web應用(前提,服務器啟動狀態))
銷毀:web應用被卸載(服務器關閉,移除該web應用)
獲得ServletContext對象:
第一種:Servlet的init方法中獲得ServletConfig 初始化方法
ServletContext servletContext = config.getServletContext ();
第二種:
ServletContext servletContext = config.getServletContext ();
ServletContext的作用:
獲得web應用中任何資源的絕對路徑(重要 重要 重要)
String path = context.getRealPath(相對于該web應用的相對地址);
public class Servlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取ServletContext對象 ServletContext context =getServletContext(); //獲取相對于服務器的相對路徑獲取絕對路徑 String patha=context.getRealPath('WEB-INF/classes/a.txt'); String pathb=context.getRealPath('b.txt'); String pathc=context.getRealPath('WEB-INF/c.txt'); //d.txt創建在WEB04文件下,不會在服務器上找到的。以后靜態資源創建在WebContent下,項目文件、配置文件在src下 System.out.println(patha); System.out.println(pathb); System.out.println(pathc); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
ServletContext是一個域對象(存儲數據的區域):
存儲數據的區域就是域對象;
ServletContext域對象的作用范圍:整個web應用(所有的web資源都可以隨意向 servletcontext域中存取數據,數據可以共享)
域對象的通用的方法:
setAtrribute(String name,Object obj); k是字符串 value是obj類型
getAttribute(String name); 強轉
removeAttribute(String name);
public class Serlvlet03 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取ServletContext對象 ServletContext context=getServletContext(); //獲取ServletContext域中的值 String name=(String)context.getAttribute('name'); response.getWriter().write(name); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
