java web项目中获取项目根路径(tomcat可运行的web源码的路径)的方式:

分为两种情况:

 

情况一:

在eclipse、inde等开发工具中获取(注:如下代码所在的类必须是控制层所在包下的类):

String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath().split("/target/")[0]+"/target/xiyinli-web-1.0-SNAPSHOT/";

其中xiyinli-web-1.0-SNAPSHOT根据自己maven的web项目中pom.xml的配置进行相应修改,我这里的如下:

    <groupId>com.xiyinli</groupId>
    <artifactId>xiyinli</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

java项目中的路径获取,request

 

情况二:

项目部署以后,在tomcat中运行时获取:

方式一:

接口中传入:HttpServletRequest

java项目中的路径获取,request

String basePath = request.getSession().getServletContext().getRealPath("/");

定时器中获取request:

        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes)ra;
        HttpServletRequest request = sra.getRequest();

方式二(一般无法拿到HttpServletRequest对象时使用,如spring定时器等):

                WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
                ServletContext servletContext = webApplicationContext.getServletContext();
                String basePath = servletContext.getRealPath("/");

 

相关文章:

  • 2022-02-07
  • 2021-05-17
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2021-08-29
  • 2021-05-25
猜你喜欢
  • 2021-11-30
  • 2021-11-30
  • 2021-11-29
  • 2022-12-23
相关资源
相似解决方案