java项目中的路径获取,request

本文介绍了在JavaWeb项目中如何获取项目的根路径,包括在开发工具中和部署到Tomcat后的不同方法。

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>

 

情况二:

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

方式一:

接口中传入:HttpServletRequest

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("/");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值