在我的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如何工作的区别以及我该如何解决?
好的,问题是通过注意Tomcat6最后没有放“/”而Tomcat8确实解决了。所以我的新代码修复了它:LOGGER.info(“为客户端获取套接字:”+客户端);
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 section。显然,它可以通过其他方式解决。此外,这个问题隐含在网上的很多地方,我只是错过了路径末尾的“/”连接,所以无法正确启动目录树。
没有简单的方法来获取tomcat主目录(我们有“conf”目录),所以我们就是这样做的。不希望改变事物,只需添加该部分代码即可。
我在网上看到了其他解决方法。