java中的相关路径获取问题

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目录
    }

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值