ServletContext接口

1.       獲取web應用(tomcatContext部分)的初始化參數。

1.1    設置初始化參數

1.1.1          tomcatserver.xml中設置Context的初始化參數。例如:

<Context path="/testcontext" docBase="/context"

         privileged="true" antiResourceLocking="false" antiJARLocking="false" debug="0" reloadable="true">

<Parameter name="name" value="zhangjianfeng" />

</Context>

在項目下的web.xml中設置Context的初始化參數。例如:

<context-param>

<param-name>age</param-name>

<param-value>24</param-value>

</context-param>

1.2    getServletContext().getInitParameter(String name)

2.       記錄日誌

2.1    設置日誌文件

server.xml文件中,使用logger元素來設置日誌文件。

<Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_log." suffix=".txt" timestamp="true"/>

2.2    this.getServletContext().log("測試")

3.       訪問資源文件

3.1    getResource(String parh)方法:其中path必須是/開頭,代表當前web應用程序的根目錄。返回返回的一個代表某個資源的URL對象。

3.2    getResoutceAsStream(String parh),返回文件流。這個好處是可以使用相對於根目錄的路徑訪問到web目錄下的所有文件,而不必知道絕對路徑。

例如在WEB-INF下新建文件me.properties,內容爲:

name=zhangjianfeng

age=24

       然後在Servlet中執行:

       this.getServletContext().getResourceAsStream("/WEB-INF/me.properties");

       Properties me = new Properties();

       me.load(is);

       out.write(me.getProperty("name"));

       out.write(me.getProperty("age"));

將會打印出zhangjianfeng24

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章