request.getRealPath() 方法已经不推荐使用
替代方法是:
request.getSession().getServletContect().getRealPath("/");
得到站点的绝对地址
在 Struts2 和 Servlet 中还可以用
Struts2: 要求 Action implements ServletContextAware 并实现相关接口
this.getServletContect().getRealPath("/");
Servlet:
this.getServlet().getServletContext().getRealPath("/");
补充:获得ClassPath的方法
String classPath = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
注意:中间将URL转成URI然后再getPath(),通过URI对象getPath()能解决路径中出现空格时表示为%20的的问题,不会对后期再定位文件带来麻烦