getContextPath、getServletPath、getRequestURI,getRealPath的區別


 

假定你的web application 項目名稱為news,你在瀏覽器中輸入請求路徑: http://localhost:8080/news/main/list.jsp 

 

則執行下面向行代碼后打印出如下結果: 
1、 System.out.println(request.getContextPath()); //可返回站點的根路徑。也就是項目的名字 
打印結果:/news 

2、System.out.println(request.getServletPath()); 
打印結果:/main/list.jsp 

3、 System.out.println(request.getRequestURI()); 
打印結果:/news/main/list.jsp 

 

4、 System.out.println(request.getRealPath("/")); 

      request.getRealPath("/")已經不建議使用。

getRealPath();

返回一個字符串,包含一個給定虛擬路徑的真實路徑。

struts2中:

ServletContext ctx=ServletActionContext.getServletContext();

String path=ctx.getRealPath("/");
String path1=ctx.getRealPath("/files/view.jsp");

輸出:path為D:\Javasoftware\apache-tomcat-7.0.70\apache-tomcat-7.0.70\webapps\struts2-1\

         path1為D:\Javasoftware\apache-tomcat-7.0.70\apache-tomcat-7.0.70\webapps\struts2-1\files\view.jsp

\files\view.jsp這部分就是虛擬路徑

D:\Javasoftware\apache-tomcat-7.0.70\apache-tomcat-7.0.70\webapps\struts2-1\  為項目的絕對路徑

 servlet中:

 

private ServletConfig  config;

public void init(ServletConfig config) throws ServletException {
this.config=config;}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

ServletContext ctx=config.getServletContext();
String temp=ctx.getRealPath("/");
}


打印結果:F:\Tomcat 6.0\webapps\news\test 

 

注:

URI=contextPath+servletPath


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM