在 Java Web 应用程序中获取上下文路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26018657/
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
Get context path in Java web application
提问by Juan Camilo Mejia
I am trying to get the project context path in Java web application. My project is located in D:\GED\WSysGED
directory, I want to get that path. In my research, I found two ways to do this: The first uses System.getProperty
like so:
我正在尝试获取 Java Web 应用程序中的项目上下文路径。我的项目位于D:\GED\WSysGED
目录中,我想获取该路径。在我的研究中,我找到了两种方法来做到这一点: 第一种用法System.getProperty
如下:
String path= System.getProperty("user.dir");
System.out.println(path);
But that code returns D:\eclipse-jee-luna-R-win32\eclipse
, where the Eclipse executable file is located.
但该代码返回D:\eclipse-jee-luna-R-win32\eclipse
Eclipse 可执行文件所在的位置。
The second way is using a servlet.
第二种方法是使用 servlet。
I created that one following this tutorial
我按照本教程创建了那个
public class ContextPathServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletContext servletContext = getServletContext();
String contextPath = servletContext.getRealPath("/");
PrintWriter out = response.getWriter();
out.println("<br/>File system context path (in TestServlet): " + contextPath);
}
}
But it is showing C:\Users\Juan\SysGED\.metadata\.plugins\org.eclipse.wst.server.core\tmp6\wtpwebapps\WSysGED
但它显示 C:\Users\Juan\SysGED\.metadata\.plugins\org.eclipse.wst.server.core\tmp6\wtpwebapps\WSysGED
What is the correct way to get the project path?
获取项目路径的正确方法是什么?
回答by Nattu
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String contextPath = request.getContextPath();
System.out.println(contextpath);
}