Java ServletContext對(duì)象用法解析
ServletContext對(duì)象:
ServletContext類似字節(jié)碼文件對(duì)象,在web創(chuàng)建的時(shí)候就自動(dòng)生成了,并且是唯一的,跟隨著項(xiàng)目和服務(wù)器共存亡了。通過這個(gè)對(duì)象,我們可以向里面存數(shù)據(jù)(鍵值對(duì)),也可以通過別的Servlet來獲取這個(gè)數(shù)據(jù);也可以根據(jù)相對(duì)(服務(wù)器)路徑繼來獲取絕對(duì)路徑。
ServletContext代表是一個(gè)web應(yīng)用的環(huán)境(上下文)對(duì)象,ServletContext對(duì)象內(nèi)部封裝是該web應(yīng)用的信息,ServletContext對(duì)象一個(gè)web應(yīng)用只有一個(gè)。 一個(gè)web應(yīng)用有幾個(gè)servlet對(duì)象?----多個(gè)
ServletContext對(duì)象的生命周期?
創(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對(duì)象:
第一種:Servlet的init方法中獲得ServletConfig 初始化方法
ServletContext servletContext = config.getServletContext ();
第二種:
ServletContext servletContext = config.getServletContext ();
ServletContext的作用:
獲得web應(yīng)用中任何資源的絕對(duì)路徑(重要 重要 重要)
String path = context.getRealPath(相對(duì)于該web應(yīng)用的相對(duì)地址);
public class Servlet01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取ServletContext對(duì)象 ServletContext context =getServletContext(); //獲取相對(duì)于服務(wù)器的相對(duì)路徑獲取絕對(duì)路徑 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對(duì)象 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); }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
