Java 如何获取 WAR 文件的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9727507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the name of the WAR file?
提问by finneycanhelp
How can a class get the name of the WAR file that is using it?
一个类如何获得使用它的 WAR 文件的名称?
This is for diagnostic purposes.
这是为了诊断目的。
采纳答案by Rahul Borkar
in servlet
在小服务程序中
String warName = new File(getServletContext().getRealPath("/")).getName();
you can use this.
你可以用这个。
回答by Mike Baranczak
ServletContext.getContextPath()
ServletContext.getContextPath()
This returns the context path of the application (or "" for the root context). Within a servlet container, no two applications will ever have the same value for this.
这将返回应用程序的上下文路径(或“”作为根上下文)。在一个 servlet 容器中,没有两个应用程序对此具有相同的值。
EDIT:
编辑:
And for those who don't know what the context path is: it's the URI prefix for the application. In most cases, it defaults to the name of the war file, unless you configure it explicitly. So if you have foo.war, then you'll access it at http://localhost:8080/foo/
, and the above function will return "/foo".
对于那些不知道上下文路径是什么的人:它是应用程序的 URI 前缀。在大多数情况下,它默认为 war 文件的名称,除非您明确配置它。因此,如果您有 foo.war,那么您将在 处访问它http://localhost:8080/foo/
,并且上述函数将返回“/foo”。