What is different between these two code lines and when should we use each of them?
1.
RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
2.
RequestDispatcher view = getServletContext().getRequestDispatcher(“/result.jsp”);
What is different between these two code lines and when should we use each of them?
1.
RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
2.
RequestDispatcher view = getServletContext().getRequestDispatcher(“/result.jsp”);
1) RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);
Here,
java doc says,
The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. This method returns null if the servlet container cannot return a RequestDispatcher.
The difference between this method and ServletContext.getRequestDispatcher(java.lang.String) is that this method can take a relative path.
2) RequestDispatcher view = getServletContext().getRequestDispatcher(“/result.jsp”);
Here,
java doc says,
The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.