一、.獲取Tomcat的Context的初始化參數(shù)。
1.獲取Tomcat的server.xml中設(shè)置Context的初始化參數(shù)。
例如:
<Context path="/testcontext" docBase="/context"
privileged="true" antiResourceLocking="false" antiJARLocking="false"
debug="0" reloadable="true">
<Parameter name="name" value="yangqisheng" />
</Context>
方式:getServletContext().getInitParameter(String name)
2.獲取在項(xiàng)目下的web.xml中設(shè)置Context的初始化參數(shù)。
例如:
<context-param>
<param-name>age</param-name>
<param-value>24</param-value>
</context-param>
方式:getServletContext().getInitParameter(String name)二、記錄Tomcat日志
1.設(shè)置日志文件
在server.xml文件中,使用logger元素來設(shè)置日志文件。
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_log." suffix=".txt" timestamp="true"/>
寫日志:this.getServletContext().log("測試")三、訪問資源文件
3.1 getResource(String parh)方法:其中path必須是/開頭,代表當(dāng)前web應(yīng)用程序的根目錄。返回返回的一個(gè)代表某個(gè)資源的URL對象。
3.2 getResoutceAsStream(String parh),返回文件流。這個(gè)好處是可以使用相對于根目錄的路徑訪問到web目錄下的所有文件,而不必知道絕對路徑。
例如在WEB-INF下新建文件me.properties,內(nèi)容為:
name=yangqisheng
age=25
this.getServletContext().getResourceAsStream("/WEB-INF/me.properties");
Properties me = new Properties();
me.load(is);
out.write(me.getProperty("name"));
out.write(me.getProperty("age"));
然后在Servlet中執(zhí)行:
將會(huì)打印出 yangqisheng25