Web中servlet開發利用getRealPath獲取路徑相關知識點總結:
在servlet開發中,經常會遇到這樣一些問題。在獲取web工程中的指定文件、URL時候,需要考慮路徑該怎麼寫,以下是在servlet中分別獲取:
web 工程目錄下、src目錄下、 webContent(WebRoot)目錄下、WEB-INF目錄下文件的過程。
爲了更簡單瞭解並區別不同目錄的路徑區別。先用JAVA SE IO流獲取文件內容。爲了演示效果,在工程下創建了四個TXT文件。
**********************************************************************************************************************************************************************************
文件目錄結構:
【1.】 使用Java SE IO 分別獲取TXT文件
public static void main(String[] args) throws IOException {
//1.0 get the src.txt file
readFile("src/src.txt");
//2.0 get the webroot.txt file
readFile("WebContent/webroot.txt");
//3.0 get the web-info.txt
readFile("WebContent/WEB-INF/webinfo.txt");
//4.0 get the project.txt
readFile("project.txt");
}
public static void readFile(String path) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(path));
String line = br.readLine();
br.close();
System.out.println("get the context in this file: " + line);
}
get the context in file: this file is located in the src directory
get the context in file: this file is located in the webroot directory
get the context in file: this file is located in the web-info directory
get the context in file: this file is located in the webproject directory
本地eclipse和tomcat服務器上文件位置對應:
本地Eclipse中文件位置 ------------ 服務器上文件位置(tomcat)
Web 工程下文件project.txt 無(訪問不到404)
Src目錄下src.txt /WEB-INF/classes/src.txt
WebRoot目錄下webroot.txt 根目錄 /webroot.txt
WEB-INF目錄下webinfo.txt /WEB-INF/webinfo.txt
【2.】 在servlet中使用getRealPath方法獲取文件路徑:
在servlet中分別獲取TXT文件。通過ServletContext的getRealPath()方法,例如context.getRealPath(“/”);獲取的是當前工程部署到tomcat服務器中的絕對磁盤路徑。
具體代碼內容如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext context = this.getServletContext();
String path = context.getRealPath("/"); // get the absolutely path of
// web project in tomcat server.
// System.out.println(path);
// 1.0 get the src.txt file
readFile(path + "WEB-INF/classes/src.txt");
//== readFile(context.getRealPath("/WEB-INF/classes/src.txt"));
// 2.0 get the webroot.txt file
readFile(path + "webroot.txt");
//== readFile(context.getRealPath("/webroot.txt"));
// 3.0 get the web-info.txt
readFile(path + "WEB-INF/webinfo.txt");
//== readFile(context.getRealPath("/WEB-INF/webinfo.txt"));
}
web開發中同時常用也可以用request域等其他域對象來獲取路徑,合理的選用最恰當的方式進行處理。