spring中获取当前项目的真实路径

总结:

方法1

WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
String realPath = servletContext.getRealPath(File.separator);//G:\ty\tomcat\tomcat-7080\webapps\crm-timer

 

方法2:

ClassLoader classLoader = this.getClass().getClassLoader();
        URL resource1 = classLoader.getResource("");
        resource1.getPath();///G:/ty/tomcat/tomcat-7080/webapps/crm-timer/WEB-INF/classes/

//或者
URL resource = classLoader.getResource("/"); String path = resource.getPath();///G:/ty/tomcat/tomcat-7080/webapps/crm-timer/WEB-INF/classes/

 

注意:上面的方法除了 URL resource1 = classLoader.getResource(""); 外,都需要在tomcat中启动项目后才会有正常值,在junit或者main方法测试的时候都是会报错的,即使getResource("")不报错,返回的地址是这样:G:/ty/wkty2/crmCust-parent/crm-timer/bin/main/

 

 

。。。。。。参考如下。。。。。。。

 

方法1:

转:

spring中获取当前项目的真实路径

如果为体现项目的层次感,当我们使用request的时候,一般都是在控制层中使用的,没有必要将request也传递到service使用,所以首先是讲一下在controller获取当前的项目的绝对路径

    public Message<Object> uploadImgsFile(HttpServletRequest request) {
    //1
    String realPath = request.getSession().getServletContext().getRealPath(File.separator);
    System.out.println(realPath);
    //2
    String realPath2 = request.getServletContext().getRealPath(File.separator);
    System.out.println(realPath2);
     
    return null;
    }

 

 

如果当前想要获取当前项目的绝对路径,而此时又不在controller,同时又不想传递request的参数到service层,可以这样操作

  1.  
     
     
        //代码片段
        //现获取当前的路径
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();
        String realPath = servletContext.getRealPath(File.separator);
        System.out.println(realPath);

     

经过上面的操作可以获取项目的路径,以此来方便自己项目的需求

。。。。。。。。。。。。。。。。

 

方法2:

转:

在java类中获取WEB-INF路径

2016.04.29 14:36* 字数 189 阅读 4699评论 0

把java项目部署到tomcat中以后,类文件的路径都在“apache-tomcat-7.0.69\webapps\APP\WEB-INF\classes”中,如果我们需要在某个java类中获取WEB-INF下的某些资源,例如现在我需要在WEB-INF下的templates文件夹下的模板资源

Paste_Image.png

就需要在java文件中这样获取classes目录,然后转到templates目录下。

private static String templatePath = TemplateFactory.class.getClassLoader().getResource("/").getPath().replace("classes", "templates"); 

其中TemplateFactory是我的Java类名,

TemplateFactory.class.getClassLoader().getResource("/").getPath()

是获取到classes文件夹下的路径,就是apache-tomcat-7.0.69\webapps\APP\WEB-INF\classes,

然后可以把classes替换为我们想要得到的文件夹名字。

参考:web项目中各种路径的获取

转载于:https://www.cnblogs.com/libin6505/p/10722389.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值