java - 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 的工作方式有所不同,我该如何解决?
解决方案
好的,通过注意到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”目录),所以我们就是这样做的。不想改变任何事情,只是添加了那部分代码以使其工作。
我在网上看到的还有其他解决方法。
推荐阅读
- java - 为什么我有这个错误?MySQLNonTransientConnectionException
- git - git:什么是树内的提交对象?
- python - Raspberry pi 3b+ 上的 IndexError 但在 PC Python 中没有
- flutter - 无法在颤振中使用构建运行器生成 mobx
- java - 连接提取的休眠问题“无法连接到基本类型的属性”
- c# - 应用程序找不到位于另一个项目中的 Razor 页面
- virtual-machine - 无法访问我家中但想从办公室访问的自托管虚拟服务器(Ubuntu 20.04)
- javascript - 对象文字、函数和 this
- flutter - 如何删除屏幕底部和底栏之间的底部空间?
- android - 在初始化 ArrayAdapter 时,我可以使用变量来代替调用数组的第二个参数的最后一部分吗?