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

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


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

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

原文地址:https://www.cnblogs.com/chen-lhx/p/4911182.html