JAVA擷取伺服器路徑的方法

來源:互聯網
上載者:User

標籤:instance   方法   eal   servlet   sep   server   config   base   local   

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(“/”);

  

 

 

 

*************************************************************************【轉】

JAVA擷取伺服器路徑的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.