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("/") + 你的路径

 

posted @ 2018-11-01 16:36  tele  阅读(11496)  评论(0编辑  收藏  举报