首页 > 解决方案 > Tomcat6 和 Tomcat8 之间的 getRealPath

问题描述

在我的 Web 应用程序中,我有以下代码:

    if( context == null )
        throw new WMSException( "Missing session context." );

    String path  = context.getRealPath("");
    if( path == null )
        throw new WMSException( "Missing context real path." );

    WebSocket ws    = new WebSocket();
    String    sep   = "/";
    int       where = path.lastIndexOf( sep );
    if( where < 0 ){
        sep   = "\\";
        where = path.lastIndexOf( sep );
    }

    path  = path.substring( 0, where );
    where = path.lastIndexOf( sep );
    path  = path.substring( 0, where ) + "/conf/wms";
    if( firstTime ){
        firstTime = false;
        System.out.println( "Getting configuration from " + path );
    }

    File      docFile = new File(path, "socket.xml");
    System.out.println( "Name " + docFile.getName() );
    System.out.println( "Path " + docFile.getPath() );

在 tomcat 6 中,由于 getRealPath 的工作方式,我得到以下信息:

/usr/share/tomcat6/conf/wms/socket.xml

在tomcat 8中,对于同一个war文件,我得到以下信息:

/opt/tomcat8/webapps/conf/wms/socket.xml

为什么 getRealPath 的工作方式有所不同,我该如何解决?

标签: javatomcat8tomcat6

解决方案


好的,通过注意到Tomcat6没有在末尾添加“/”但Tomcat8确实可以解决问题。所以我的新代码修复了它:LOGGER.info("Get socket for client:" + client);

    if( context == null )
        throw new WMSException( "Missing session context." );

    String path  = context.getRealPath("");
    if( path == null )
        throw new WMSException( "Missing context real path." );

    LOGGER.info( "Path 1 '" + path + "'");

    WebSocket ws    = new WebSocket();
    String    sep   = "/";
    int       where = path.lastIndexOf( sep );
    if( where < 0 ){
        sep   = "\\";
        where = path.lastIndexOf( sep );
    }

    String newPath  = path.substring( 0, where );
    if( newPath.equals(path.substring(0, path.length() - 1 )))
    {
        where = newPath.lastIndexOf( sep );
        path  = newPath.substring( 0, where );
        LOGGER.info( "Path 2a '" + path + "'");
    }
    else
        path = newPath;

    LOGGER.info( "Path 2 '" + path + "'");
    where = path.lastIndexOf( sep );
    path  = path.substring( 0, where ) + "/conf/wms";
    LOGGER.info( "Path 3 '" + path + "'");
    if( firstTime ){
        firstTime = false;
        LOGGER.info( "Getting configuration from " + path );
    }

    LOGGER.info( "Path 4 '" + path + "'");
    File      docFile = new File(path, "socket.xml");
    LOGGER.info( "Name '" + docFile.getName() + "';Path '" + docFile.getPath() + "'");

关键是if( newPath.equals(path.substring(0, path.length() - 1 )))if 部分。显然,它可以通过其他方式解决。另外,这个问题在网上很多地方都有暗示,我只是错过了路径末尾“/”的连接,所以它无法正确地向上目录树。

没有简单的方法来获取 tomcat 主目录(我们有“conf”目录),所以我们就是这样做的。不想改变任何事情,只是添加了那部分代码以使其工作。

我在网上看到的还有其他解决方法。


推荐阅读