Fork me on GitHub

获取javaweb的路径

java类获取classpath路径

获取WEB-INF/class路径。

this.getClass().getResource("/").getPath()

根据user.dir获取的路径在java项目中获取项目路径,而在web项目中获取的是tomcat/bin下面。

System.getProperty("user.dir")

传统Web项目(非maven)获取web路径

获取项目绝对路径(空格会转义为20%,空格、+号、中文不行)

/*获取项目路径*/
Thread.currentThread().getContextClassLoader().getResource("../../")
/*获取/WEB-INF/classes绝对路径*/
Thread.currentThread().getContextClassLoader().getResource("")

使用repaceAll("%20",' ')替换,但只能解决空格问题,如果路径中包含其他特殊字符和中文就不能解决问题。

使用URLDecoder.decode(str,"UTF-8")解码,但是只能解决一部分,若路径中含有+,也是不能解决的。原因是+号被解码后变成空格

//获取项目路径;路径可以有空格,但是不可以有+号
String projectPath = URLDecoder.decode(Thread.currentThread().getContextClassLoader().getResource("../../").getPath(),"utf-8");

Servlet中获取项目路径

获取项目路径

request.getSession().getServletContext().getRealPath("")

JSP中获取项目路径

jsp中获取项目路径

new java.io.File(application.getRealPath(request.getRequestURI())).getParent();

参考:

https://blog.csdn.net/qq_34445857/article/details/79223526

 

posted @ 2020-03-09 23:13  秋夜雨巷  阅读(297)  评论(0编辑  收藏  举报