Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get context path in Java web application

Tags:

java

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?

like image 273
Juan Camilo Mejia Avatar asked Nov 10 '22 01:11

Juan Camilo Mejia


1 Answers

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

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

    }
like image 121
Nattu Avatar answered Nov 15 '22 13:11

Nattu