resin容器下获取web-app的绝对路径

作者: 2hei 发表于2009年2月14日 12:46
版权声明: 可以转载, 转载时务必以超链形式标明文章原始出处和作者信息及版权声明
http://www.2hei.net/mt/2009/02/resin-web-app-path.html
为了获得web-app目录中的.properties文件,需要先取得web-app的WEB-INF目录,网上有很多的方法,大致描述如下:

1、java程序中中获得
System.out.println("1"+Thread.currentThread().getContextClassLoader().getResource(""));
System.out.println("2"+TestPath.class.getResource(""));
System.out.println("3"+TestPath.class.getResource("/"));
System.out.println("4"+TestPath.class.getClassLoader().getResource(""));
System.out.println("5"+ClassLoader.getSystemResource(""));
System.out.println("6"+TestPath.class.getClassLoader().getResource("src.com.2hei.net.util"));
System.out.println("7"+new File("").getAbsolutePath());


2、在jsp中获得web-app目录


根目录:request.getRequestURI()
文件的绝对路径  :application.getRealPath(request.getRequestURI());
当前web应用的绝对路径 :application.getRealPath("/");


3、Servlet中获得当前应用的相对路径和绝对路径
根目录:request.getServletPath();
文件的绝对路径 :
javax.servlet.http.HttpSession.getServletContext()
request.getSession().getServletContext().getRealPath
当前web应用的绝对路径 :servletConfig.getServletContext().getRealPath("/");

但是我遇到的问题是使用java来获得web-app目录始终得到的是容器的root目录,比如我使用的是resin3.1.6,使用java程序获得的目录始终都是/home/resin-3.1.6。
想尽了办法,把caucho.com的文档翻了个遍,也尝试了class-loader等resource等配置,始终无法配置好,我又不想使用jsp或者servlet来获取,于是想到了如下的土办法。

resin.conf 或者resin.xml中配置(详见resin-doc)
  <env-entry>
    <env-entry-name>greeting</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>I‘m 2hei</env-entry-value>
  </env-entry>


调用方法:
  public void init()
    throws ServletException
  {
    try {
      Context env =
        (Context) new InitialContext().lookup("java:comp/env");
      greeting = (String) env.lookup("greeting");
    } catch (NamingException e) {
      throw new ServletException(e);
    }
  }
然而,见证奇迹的时刻终于到来了!
现有java文件编译后是给打成了jar包来进行发布,放到了WEB-INF/lib目录中,这样使用java获得的web-app位置就是resin的home目录
我尝试不打jar包,将class放到WEB-INF/classes中,使用java来获取应用程序的绝对路径居然可以了,真不知道resin是如何加载jar包的。汗ing。。。

不过既然问题解决了,就此记录下来,以作备忘。

再者,今天是2.14 情人节,就祝愿天下有情人终成眷属!
| | Comments (0) | TrackBacks (0)

发表一个评论

关于这篇文章

这篇文章由2hei2009年2月14日 12:46发布.

上一篇:将应用程序添加到右键的方法,just like UE

下一篇:发现新的web server “JWSB1”

回到首页 或者查看归档文章

  • Powered by FeedBurner
  • Add to Google Reader or Homepage
  • Add to My AOL
  • Subscribe in NewsGator Online
  • del.icio.us/2heidel.icio.us/2hei
  • Subscribe to feed feeds