Java ServletContext對象用法解析
ServletContext對象:
ServletContext類似字節(jié)碼文件對象,在web創(chuàng)建的時(shí)候就自動(dòng)生成了,并且是唯一的,跟隨著項(xiàng)目和服務(wù)器共存亡了。通過這個(gè)對象,我們可以向里面存數(shù)據(jù)(鍵值對),也可以通過別的Servlet來獲取這個(gè)數(shù)據(jù);也可以根據(jù)相對(服務(wù)器)路徑繼來獲取絕對路徑。
ServletContext代表是一個(gè)web應(yīng)用的環(huán)境(上下文)對象,ServletContext對象內(nèi)部封裝是該web應(yīng)用的信息,ServletContext對象一個(gè)web應(yīng)用只有一個(gè)。 一個(gè)web應(yīng)用有幾個(gè)servlet對象?----多個(gè)
ServletContext對象的生命周期?
創(chuàng)建:該web應(yīng)用被加載(服務(wù)器啟動(dòng)或發(fā)布web應(yīng)用(前提,服務(wù)器啟動(dòng)狀態(tài)))
銷毀:web應(yīng)用被卸載(服務(wù)器關(guān)閉,移除該web應(yīng)用)
獲得ServletContext對象:
第一種:Servlet的init方法中獲得ServletConfig 初始化方法
ServletContext servletContext = config.getServletContext ();
第二種:
ServletContext servletContext = config.getServletContext ();
ServletContext的作用:
獲得web應(yīng)用中任何資源的絕對路徑(重要 重要 重要)
String path = context.getRealPath(相對于該web應(yīng)用的相對地址);
public class Servlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取ServletContext對象 ServletContext context =getServletContext(); //獲取相對于服務(wù)器的相對路徑獲取絕對路徑 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創(chuàng)建在WEB04文件下,不會(huì)在服務(wù)器上找到的。以后靜態(tài)資源創(chuàng)建在WebContent下,項(xiàng)目文件、配置文件在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是一個(gè)域?qū)ο螅ù鎯?chǔ)數(shù)據(jù)的區(qū)域):
存儲(chǔ)數(shù)據(jù)的區(qū)域就是域?qū)ο螅?/p>
ServletContext域?qū)ο蟮淖饔梅秶赫麄€(gè)web應(yīng)用(所有的web資源都可以隨意向 servletcontext域中存取數(shù)據(jù),數(shù)據(jù)可以共享)
域?qū)ο蟮耐ㄓ玫姆椒ǎ?/b>
setAtrribute(String name,Object obj); k是字符串 value是obj類型
getAttribute(String name); 強(qiáng)轉(zhuǎn)
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); }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python多線程操作之互斥鎖、遞歸鎖、信號量、事件實(shí)例詳解2. Python常用GUI框架原理解析匯總3. XML入門的常見問題(一)4. Django程序的優(yōu)化技巧5. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐6. idea設(shè)置自動(dòng)導(dǎo)入依賴的方法步驟7. jsp EL表達(dá)式詳解8. 怎樣才能用js生成xmldom對象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?9. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實(shí)現(xiàn)10. django 鏈接多個(gè)數(shù)據(jù)庫 并使用原生sql實(shí)現(xiàn)
