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

1.在任意的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等的符號。

2.可以在servlet的init方法裏
String path = getServletContext().getRealPath("/");
這將獲取web項目的全路徑
例如:/eclipse/workspace/tree/
tree是web項目的根目錄

3.request.getContextPath();
獲得web根的上下文環境
如 /tree
tree是web項目的root context

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章