zoukankan      html  css  js  c++  java
  • ServletContext中常用方法(getRsource和getResourceAsStream)

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

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

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

    例如:

    [html] view plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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

    转载请保留出处~!

  • 相关阅读:
    十大Intellij IDEA快捷键
    多媒体播放API 生命周期束&简介
    Bitmap
    Activity
    Android中的Handler总结
    Bitmap2
    smartimageview和多线程
    Service
    微软面试题 博弈论 经典案例 (参考答案)
    ANR和消息机制
  • 原文地址:https://www.cnblogs.com/x_wukong/p/3719933.html
Copyright © 2011-2022 走看看