如何在普通 Java 类中找到上下文路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18846553/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:35:24  来源:igfitidea点击:

How can I find context path in normal Java class

javapath

提问by Hanumath

I want to find context path of my web Application in normal Java class.If I find I can specify paths like this /Rod1/thermalMap.exewherever I need.

我想在普通的 Java 类中找到我的 Web 应用程序的上下文路径。如果我发现我可以/Rod1/thermalMap.exe在任何需要的地方指定这样的路径。

I know, How to find in servletusing the following code

我知道,如何servlet使用以下代码查找

   getServletContext().getRealPath("");

My webApps folder in the following way.

我的 webApps 文件夹如下所示。

image

图片

回答by ZaoTaoBao

Have you try this?

你试过这个吗?

 String path = new File(".").getCanonicalPath();

回答by Debojit Saikia

You can get the absolute path to to your webApp/WEB-INF/classesdirectory as below:

您可以获得webApp/WEB-INF/classes目录的绝对路径,如下所示:

URL resource = getClass().getResource("/");
String path = resource.getPath();

This will return you an absolute path like this:

这将返回一个绝对路径,如下所示:

/C:/SERVERS/x/y/x/yourApp/WEB-INF/classes

And from this you can get the path to the yourAppdirectory:

从这里你可以得到yourApp目录的路径:

path = path.replace("WEB-INF/classes/", "");

which you can use to specify paths like /Rod1/thermalMap.exe, by appending to this path.

您可以使用它来指定路径,例如/Rod1/thermalMap.exe通过附加到 this path

回答by Michael B?ckling

You need to register a

您需要注册一个

javax.servlet.ServletContextListener

in your web.xml like this:

在您的 web.xml 中,如下所示:

<listener>
    <listener-class>com.my.Servlet</listener-class>
</listener>

From that, you can get the ServletContext on which you can call getContextPath().

从中,您可以获得可以调用 getContextPath() 的 ServletContext。