servletcontext 使用解析
簡介:
每個應用都會有一個ServletContext對象與之關聯,當容器分布在在多個虛擬機上時,web應用在所分布的每個虛擬機上都擁有一個ServletContext實例.缺省情況下,ServletContext不是分布式的,并且只存在于一個虛擬機上。
通過ServletContext可以訪問應用范圍的初始化參數和屬性。
| ServletContext | getContext(String?uripath) |
| ?String | getInitParameter(String?name) |
| void | setAttribute(String?name, Object?object) |
| Object | getAttribute(String?name) |
| RequestDispatcher | getRequestDispatcher(String?path) |
| ?String | getRealPath(String?path) |
| RequestDispatcher | getRequestDispatcher(String?path) |
| ?Set | getResourcePaths(String?path) |
1).初始化參數
ServletContext對象是在Web應用程序裝載時初始化的。正像Servlet具有初始化參數一樣,ServletContext也有初始化參數。Servlet上下文初始化參數指定應用程序范圍內的信息。[1]
在web.xml中配置初始化參數:
<context-param>元素是針對整個應用的,所以并不嵌套在某個<servlet>元素中,該元素是<web-app>元 素的直接子元素。[1]
從Servlet中訪問初始化參數:
2).屬性
可以通過編程的方式綁定,也可以作為web應用的全局變量被所有Servlet和JSPs訪問
設置Context屬性:
獲取Context屬性:
ServletContext application=this.getServletContext(); Enumberation persons=application.getAttributeNames(); while(persons.hasMoreElements()){ String name=(String)persons.nextElement(); Person p=(Person)persons.getAttribute(name); application.removeAttribute(name);在Web應用范圍內存取共享數據的方法:
setAttribute(String name,java.lang.Objectobject):把一個java 對象和一個屬性名綁定,并存放到ServletContext 中,參數name 指定屬性名,參數Object 表示共享數據。
getAttribute(String name):根據參數給定的屬性名,返回一個Object類型的對象。
getAttributeNames():返回一個Enumeration 對象,該對象包含了所有存放在ServletContext 中的屬性名
removeAttribute(String name) : 根 據 參 數 指 定 的 屬 性 名 , 從servletContext 對象中刪除匹配的屬性。
getRealPath("/"):得到絕對路徑
實例:
?舉個實例:讀配置文件:
ServletContext ctx = this.getServletContext(); String INFPath = ctx.getRealPath("/WEB-INF/"); LicenseSysConst.webInfPath = INFPath; PropertyConfigurator.configure(LicenseSysConst.webInfPath + "/log4j.properties"); LicenseSysConst.propsPath = LicenseSysConst.webInfPath + "/cfg.properties";?
轉載于:https://www.cnblogs.com/trustnature/articles/3301428.html
總結
以上是生活随笔為你收集整理的servletcontext 使用解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: poj 2531(dfs)
- 下一篇: 其他-私人♂收藏(比赛记录 Mar, 2