总结:

方法1

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
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中获取当前项目的真实路径

2018年12月31日 22:12:25 小小踏浪神行 阅读数:420  

如果为体现项目的层次感,当我们使用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路径

spring中获取当前项目的真实路径 随笔 第1张 lunabird 2016.04.29 14:36* 字数 189 阅读 4699评论 0喜欢 5

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

spring中获取当前项目的真实路径 随笔 第2张 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项目中各种路径的获取

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄