zoukankan      html  css  js  c++  java
  • java项目中的路径获取,request

    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("/");
  • 相关阅读:
    同一账号在不同浏览器不能同时登录
    子页面像父页面传递参数--数组
    bootstaptable动态合并单元格和jxls动态合并单元格
    RedisTemplate的使用
    java项目中读取配置文件
    httpclient调用接口
    drop、truncate和delete的区别
    函数式编程
    常见配置redis.conf介绍
    mysql和redis加入到windows服务
  • 原文地址:https://www.cnblogs.com/007sx/p/7567605.html
Copyright © 2011-2022 走看看