1.前端获取路径
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
<head>
<base href="<%=basePath%>">
</head>
request.getContextPath():应用程序名称
request.getScheme():协议(http)
request.getServerName():ip地址
request.getServerPort():端口号
2.后台获取路径
//user.dir:用户当前的工作目录,如tomcat的bin目录 String tomcatBinPath = System.getProperty("user.dir");
//初始化上传路径 -- 获取webapps的路径
private String initUploadPath(){
String tomcatBinPath = System.getProperty("user.dir");
logger.info("tomcatBinPath:" + tomcatBinPath);
String ctxPath = null;
if(tomcatBinPath.contains("bin")){
ctxPath = tomcatBinPath.replace("\\bin", "\\webapps\\");
logger.info("replace ctxPath:" + ctxPath);
}else{
ctxPath = tomcatBinPath + "\\webapps\\";
logger.info("add ctxPath:" + ctxPath);
}
return ctxPath;
}
//获取class路径--两种方式输出都为: /E:/Projection/HelloSpring/build/web/WEB-INF/classes/
private String initUploadPath(){
String fullPath = SystemListener.class.getResource("/").getPath();
System.out.println("SystemListener.class.getResource(/).getPath(): " + fullPath);
String classLoaderPath = SystemListener.class.getClassLoader().getResource("/").getPath();
System.out.println("SystemListener.class.getClassLoader().getResource(/).getPath(): " + classLoaderPath);
}