java中取得上下文路径的方法

 

1.request.getContextPath();
获得web根的上下文环境
如 /tree
tree是web项目的root context


2.可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如:\eclipse\workspace\tree\
tree是web项目的根目录

 

3.在任意的class里调用
URLDecoder.decode(this.getClass().getClassLoader().getResource("/").getPath(), "UTF-8");
将获得当前class的全路径。
如 : C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\clientweb\WEB-INF\classes
其中,URLDecoder.decode负责把编码还原,不然路径中就会有类似于%20%ED等的符号。

posted @ 2015-10-26 14:43  龙昊雪  阅读(1247)  评论(0编辑  收藏  举报