国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Java ServletContext對象用法解析

瀏覽:2日期:2022-09-01 09:11:15

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); }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 江口县| 镶黄旗| 唐山市| 丽水市| 洛扎县| 江永县| 息烽县| 长丰县| 青冈县| 焉耆| 大厂| 霍邱县| 密山市| 札达县| 郓城县| 东乡族自治县| 和龙市| 新密市| 东源县| 屯门区| 泰来县| 茂名市| 岑溪市| 渭源县| 乌鲁木齐县| 大同县| 平南县| 神池县| 金塔县| 宜宾市| 阳信县| 阿拉善右旗| 怀安县| 弥渡县| 长岛县| 玉树县| 阜南县| 郑州市| 定远县| 卓资县| 胶南市|