我正在尝试在Java Web应用程序中获取项目上下文路径。我的项目位于D:\GED\WSysGED
目录中,我想要获取该路径。在我的研究中,我找到了两种方法来实现这一点:第一种使用System.getProperty
,如下所示:
String path= System.getProperty("user.dir");
System.out.println(path);
第一种方法是使用Java的Class.getProtectionDomain().getCodeSource().getLocation().getPath()
方法。
但该代码返回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);
}
}
但是它显示的是C:\Users\Juan\SysGED\.metadata\.plugins\org.eclipse.wst.server.core\tmp6\wtpwebapps\WSysGED
获取项目路径的正确方法是什么?