Juan Camilo Mejia
Juan Camilo Mejia

Reputation: 1012

Get context path in Java web application

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:

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.

The second way is using a 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

What is the correct way to get the project path?

Upvotes: 5

Views: 41844

Answers (1)

Nattu
Nattu

Reputation: 31

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

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

    }

Upvotes: 3

Related Questions