1、jsp页面上获取web目录路径,一般用于css、js、image等文件的加载
<%
String CONTEXT_PATH = request.getContextPath();
%>
2、java文件中获取web目录的路径,一般用于上传、下载文件
// 文件存放的相对地址
String webPath = "/upload/excel/";
// 得到存储地址
String targetDirectory = ServletActionContext.getServletContext().getRealPath(webPath);
String currentPath = ServletActionContext.getRequest().getScheme()
+ "://"
+ ServletActionContext.getRequest().getServerName()
+ ":"
+ ServletActionContext.getRequest().getServerPort()
+ ServletActionContext.getRequest().getContextPath()
+ webPath;
3、java文件中获取classpath路径,一般用于上传、下载、创建文件等
注:以下两头如果classpath同级目录由多个就不确定找到的是“classes”目录(例如我们的项目含"classes"和"test-classes"两个目录,那么总是找到“test-classes”目录,而如果在编译后把“test-classes”删去,则找到的就是"classes"路径了),好在项目部署时只部署"classes"目录
String n = getClass().getResource("/").getFile();
String m = this.getClass().getClassLoader().getResource("").getPath();
4、java文件中获得当前目录路径,一般用于上传、下载、创建文件等
、、、
String path = System.getProperty("java.io.tempdir"); File file = new File(path + "temp" + File.separator + "mapping"); if (!file.exists()) { file.mkdirs(); } Properties city = new Properties(); city.put("SHANGHAI", "上海"); city.put("CNY", "元"); city.store(new FileOutputStream(file.getAbsolutePath() + File.separator + fILENAME), fILENAME); mappingService = new MappingService(); mappingService.setIsStore(Boolean.FALSE); mappingService.setMappingResourcesPath(file.getAbsolutePath());//file 的全路径,不包括 file name
5、在只使用spring的环境中需要在bean上实现 ServletContextAware:
publid class Xbean implements ServletContextAware {
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
String webapp = servletContext.getRealPath("/");//得到web目录
}
}