//在Servlet與JSP中取得當前檔案所在的相對路徑與絕對路徑
JSP中
根目錄所對應的絕對路徑:request.getRequestURI()
檔案的絕對路徑 :application.getRealPath(request.getRequestURI());
當前web應用的絕對路徑 :application.getRealPath("/");
取得請求檔案的上層目錄:new File(application.getRealPath(request.getRequestURI())).getParent()
3.2 Servlet中獲得當前應用的相對路徑和絕對路徑
根目錄所對應的絕對路徑:request.getServletPath();
檔案的絕對路徑 :request.getSession().getServletContext().getRealPath
(request.getRequestURI())
當前web應用的絕對路徑 :servletConfig.getServletContext().getRealPath("/");
代碼如下 |
複製代碼 |
out.println("根目錄所對應的絕對路徑:" + request.getRequestURI() + "<br/>"); String strPathFile = application.getRealPath(request.getRequestURI()); out.println("檔案的絕對路徑:" + strPathFile+ "<br/>"); out.println(application.getRealPath(request.getRequestURI())); String strDirPath = new File(application.getRealPath(request.getRequestURI())).getParent(); out.println("目錄的絕對路徑:" + strDirPath + "<br/>");
|
程式
代碼如下 |
複製代碼 |
String classPath = this.getClass().getClassLoader().getResource("/").getPath(); try { classPath =URLDecoder.decode(classPath, "gb2312"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); }
|
例子
代碼如下 |
複製代碼 |
<body> 當前WEB應用的實體路徑:<%=application.getRealPath("/")%><BR> 當前你求請的JSP檔案的實體路徑:<%=application.getRealPath(request.getRequestURI())%><BR> <% String path=application.getRealPath(request.getRequestURI()); String dir=new File(path).getParent(); out.println("當前JSP檔案所在目錄的實體路徑"+dir+"</br>"); String realPath1 = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+request.getServletPath().substring(0,request.getServletPath().lastIndexOf("/")+1); out.println("web URL 路徑:"+realPath1); %> </body> |
servlet中獲得項目絕對路徑
String filePath=this.getServletConfig().getServletContext().getRealPath("/");
根目錄所對應的絕對路徑:request.getServletPath();
檔案的絕對路徑 :request.getSession().getServletContext().getRealPath(request.getRequestURI())
當前web應用的絕對路徑 :servletConfig.getServletContext().getRealPath("/");
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("/"); |
例
//JSP中的application對象就是Servlet中的ServerContext,所以在Servlet中是如此獲得
//import java.io.File;
System.out.println("根目錄所對應的絕對路徑:" + request.getServletPath() + "<br/>");
String strPathFile = request.getSession().getServletContext().getRealPath(request.getRequestURI());
System.out.println("檔案的絕對路徑:" + strPathFile + "<br/>");
String strDirPath = new File(request.getSession().getServletContext().getRealPath(request.getRequestURI())).getParent();
System.out.println("目錄的絕對路徑:" + strDirPath + "<br/>");
檔案名稱不能包括以下字元:/:*?"<>|
擷取Web項目的全路徑
String strDirPath = getServletContext().getRealPath("/");