• 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("/");
  • 相关阅读:
    ip聚合(百度之星资格赛1003)
    encoding(hdoj1020)
    Candy Sharing Game(hdoj1034)
    you can Solve a Geometry Problem too(hdoj1086)
    Holding Bin-Laden Captive!(hdoj1085)代码并未完全看懂
    Computer Transformation(hdoj 1041)
    Digital Roots(hdoj1013)
    humble number(hd1058)
    FatMouse' Trade(hdoj1009)
    1021 Fibonacci Again (hdoj)
  • 原文地址:https://www.cnblogs.com/007sx/p/7567605.html
Copyright © 2020-2023  润新知