现在的位置: 首页 > 综合 > 正文

ServletContext中常用方法

2014年01月22日 ⁄ 综合 ⁄ 共 1193字 ⁄ 字号 评论关闭

一、.获取Tomcat的Context的初始化参数。

1.获取Tomcat的server.xml中设置Context的初始化参数。

例如:

<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.获取在项目下的web.xml中设置Context的初始化参数。

例如:

<context-param>
    <param-name>age</param-name>
    <param-value>24</param-value>
</context-param>

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

二、记录Tomcat日志

1.设置日志文件

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

<Logger className="org.apache.catalina.logger.FileLogger" 
        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

       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中执行:

将会打印出 yangqisheng25

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

转载请保留出处~!

抱歉!评论已关闭.