Issue
I have a project in Netbeans. In "Source Packages" I have a servlet, myServlet.java. But it is inside folders. Its com.login.controller. In "Web Pages" I have 2 JSPs, login.jsp
and home.jsp
. login.jsp
is inside of folder "jsp/login/login.jsp"
while home.jsp is at "jsp/home/home.jsp".
Now my question is what is the best way of invoking JSP page from servlet when using getRequestDispatcher? In my login.jsp when I clicked login button it call myServlet.java and then it will process if the inputs are valid it should then directed in home.jsp using getRequestDispatcher. What Should I enter in its parameter as path? What I thought are the ff:
getRequestDispatcher("home.jsp");
getRequestDispatcher("jsp/home/home.jsp");
getRequestDispatcher("../../../jsp/home/home.jsp"); //Getting back of
directory 3x because I thought my servlet is inside 3 folders that's why.
But all of these 3 did not work. What should I do? I don't know. Please help me. Thanks in advance.
Solution
Make use of contextpath, it will give you root path.
request.getContextPath()
So if you want to access home.jsp, navigate from Web-Content folder i.e
getRequestDispatcher(request.getContextPath()+"/jsp/home/home.jsp");
Similarly, when you want to send request to Servlet, you can use
getRequestDispatcher(request.getContextPath()+"/myServlet.java");
Answered By - Neha Shettar