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(“/”);
*************************************************************************【轉】