java获取项目路径的几种方法总结

前端获取当前项目路径:

 <script type="text/javascript">
    //项目上下文
    var context="<%=request.getContextPath()%>";
</script>

后台:
1.得到当前工程的根路径,代码如下
String path = request.getContextPath();

2.得到登录的计算机域名,如果没有域名就得到IP
request.getRemoteHost();

3.得到登录计算机的IP
request.getRemoteAddr();

4.例如:
String path = request.getContextPath();
String basePath = request.getScheme()+”://”+request.getServerName()+”:”+request.getServerPort()+path+”/”;

一般我们做项目时候基本都会碰到上传文件,本人亲测,上传文件后端必须得用绝对路径,用http://IP:80/项目名 的路径方法是行不通的。但是有时候由于服务器的分布式布局,绝对路径写死是很麻烦的时候,所以最后是从代码中读取路径。

1、String path = request.getContextPath();
运行在Tomcat得到的路径 /talentrecommend01

2、String path1 = System.getProperty(“user.dir”);
运行在Tomcat上得到的路径 E:\apache-tomcat-7.0.65\bin
未运行Tomcat时得到的路径 E:\myeclipse\project\talentrecommend01
System.getProperty(“参数”),根据参数的不同可以得到很多值,具体有哪些参数可百度。

3、String path2 = request.getServletContext().getRealPath(“/”) ;
运行在Tomcat服务器上得到的路径 E:\apache-tomcat-7.0.65\webapps\talentrecommend01\

这三种最常用的方法是3,最好有个办法把path2放在一个全局变量中,且在项目运行时候生成一次,项目结束时候摧毁
知识有限,我只把它单独放在一个类中

public class SystemUtil {
/**
* @author cy
* @description 得到项目的根目录的绝对路径
*/
public static String getPath(HttpServletRequest request){
String path = request.getServletContext().getRealPath(“/”);
path = path.replaceAll(“\\”, “/”);
return path;
}
}

个人检测:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_21223653/article/details/80339316