在Java Web应用程序中获取上下文路径

Jua*_*jia 6 java

我试图在Java Web应用程序中获取项目上下文路径.我的项目位于D:\GED\WSysGED目录中,我希望获得该路径.在我的研究中,我发现了两种方法:首先使用System.getProperty如下:

String path= System.getProperty("user.dir");  
System.out.println(path);
Run Code Online (Sandbox Code Playgroud)

但是该代码返回D:\eclipse-jee-luna-R-win32\eclipse,Eclipse可执行文件所在的位置.

第二种方法是使用servlet.

我在本教程后创建了一个

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但它正在显示 C:\Users\Juan\SysGED\.metadata\.plugins\org.eclipse.wst.server.core\tmp6\wtpwebapps\WSysGED

获得项目路径的正确方法是什么?

小智 3

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String contextPath = request.getContextPath();
        System.out.println(contextpath);

    }
Run Code Online (Sandbox Code Playgroud)

  • 请编辑更多信息。不鼓励仅使用代码和“尝试这个”答案,因为它们不包含可搜索的内容,并且不解释为什么有人应该“尝试这个”。 (5认同)
  • 请添加更多信息。你是如何得出这个结论的?除了复制粘贴您的代码之外,我们可以在哪里验证您的解决方案是否正确?为什么它有效? (2认同)