1. 程式人生 > >JAVA獲取伺服器路徑的方法

JAVA獲取伺服器路徑的方法

1、在JSF環境中獲取到ServletContext:
ServletContext sc = (ServletContext)FacesContext.
        getCurrentInstance().getExternalContext().getContext(); 
2、servlet中獲得專案絕對路徑

String filePath=this.getServletConfig().
        getServletContext().getRealPath("/"); 

根目錄所對應的絕對路徑
request.getServletPath();
檔案的絕對路徑
request.getSession().getServletContext().getRealPath(request.getRequestURI())
當前web應用的絕對路徑
servletConfig.getServletContext().getRealPath(“/”);
3、jsp中獲取伺服器路徑


String contextPath = request.getContextPath();    
String realPath = request.getSession().
                getServletContext().getRealPath("/");    
String basePath = request.getScheme()+"://"+request.getServerName()+":"+
                request.getServerPort()+contextPath+"/";
說明:
contextPath =”/專案名稱”; //獲取的是專案的相對路徑
realPath = F:\tomcat_home\webapps\專案名稱\ //獲取的是專案的絕對路徑
basePath = http://localhost:8080/專案名稱/ //獲取的是服務的訪問地址
4、ServletContext物件獲得幾種方式


Javax.servlet.http.HttpSession.getServletContext() 
Javax.servlet.jsp.PageContext.getServletContext()
Javax.servlet.ServletConfig.getServletContext()
檔案的絕對路徑
request.getSession().getServletContext().getRealPath(request.getRequestURI())
當前web應用的絕對路徑
servletConfig.getServletContext().getRealPath(“/”);