ServletContext中常用方法(getRsource和getResourceAsStream)


轉自:http://blog.csdn.net/yakson/article/details/9203267

 

一、.獲取Tomcat的Context的初始化參數。

1.獲取Tomcat的server.xml中設置Context的初始化參數。

例如:

 

[html]  view plain copy
 
  1. <Context path="/testcontext" docBase="/context"  
  2.          privileged="true" antiResourceLocking="false" antiJARLocking="false"  
  3.          debug="0" reloadable="true">  
  4.     <Parameter name="name" value="yangqisheng" />  
  5. </Context>  

方式:getServletContext().getInitParameter(String name)

2.獲取在項目下的web.xml中設置Context的初始化參數。

例如:

 

[html]  view plain copy
 
  1. <context-param>  
  2.     <param-name>age</param-name>  
  3.     <param-value>24</param-value>  
  4. </context-param>  

 

方式:getServletContext().getInitParameter(String name)

二、記錄Tomcat日志

1.設置日志文件

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

[html]  view plain copy
 
  1. <Logger className="org.apache.catalina.logger.FileLogger"   
  2.         prefix="localhost_log." suffix=".txt" timestamp="true"/>  

 

寫日志:this.getServletContext().log("測試")

三、訪問資源文件

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

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

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

name=yangqisheng

age=25

 

[java]  view plain copy
 
  1. this.getServletContext().getResourceAsStream("/WEB-INF/me.properties");  
  2. Properties me = new Properties();  
  3. me.load(this.getServletContext().getResourceAsStream("/WEB-INF/me.properties"));  
  4. out.write(me.getProperty("name"));  
  5. out.write(me.getProperty("age"));  

然后在Servlet中執行:

將會打印出 yangqisheng25

 

本文地址:http://blog.csdn.net/yakson/article/details/9203267

轉載請保留出處~!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM