1. 程式人生 > >request.getSession().getServletContext().getRealPath()的一些坑

request.getSession().getServletContext().getRealPath()的一些坑

今天是學校機房的伺服器上對之前的一個網站升級時發現了一個bug,我自己的機器上用的tomcat8,機房上是tomcat7,結果一執行就開始報找不到檔案,最後發現是檔案分隔符的問題

原來在程式碼中涉及到路徑的寫法是request.getSession().getServletContext().getRealPath("/WEB-INF/"),總是File Not Found.於是修改為request.getSession().getServletContext().getRealPath("/") +"WEB-INF"+"/",重新編譯執行後正常,很奇葩的問題下午抽個時間又對request.getSession().getServletContext().getRealPath()進行了一番測試,發現即使使用File.separator也沒用,注意第5行結果

1 System.out.println(request.getSession().getServletContext().getRealPath(""));   G:\apache-tomcat-8.5.24\webapps\servlet\
2 System.out.println(request.getSession().getServletContext().getRealPath("/"));  G:\apache-tomcat-8.5.24\webapps\servlet\
3 System.out.println(request.getSession().getServletContext().getRealPath(File.separator)); G:\apache-tomcat-8.5.24\webapps\servlet
4 System.out.println(request.getSession().getServletContext().getRealPath(File.separator+ "WEB-INF")); G:\apache-tomcat-8.5.24\webapps\servlet\WEB-INF 5 System.out.println(request.getSession().getServletContext().getRealPath(File.separator + "WEB-INF" + File.separator)); G:\apache-tomcat-8.5.24\webapps\servlet\WEB-INF
6 System.out.println(request.getSession().getServletContext().getRealPath("/WEB-INF/"));G:\apache-tomcat-8.5.24\webapps\servlet\WEB-INF\

推薦寫法request.getSession().getServletContext().getRealPath("/") + 你的路徑