Difference between RequestDispatcher and sendRedirect
First we will look at the differences between the two.
request.getRequestDispatcher(String path)
path need not begin with ‘/’. If path starts with ‘/’ then this also works like
servletContext.getRequestDispatcher(String path)
This can accept path relative to request path or relative to context root path.
Ex: 1
In request, http://localhost:8080/RequestDispatcherExampleApp/s1/page1.jsp
Context root is /RequestDispatcherExampleApp
Relative path to request is /RequestDispatcherExampleApp/s1/
So, request.getRequestDispatcher(“page2.jsp”) while processing the request for
http://localhost:8080/RequestDispatcherExampleApp/s1/page1.jsp will look for page2.jsp under directory /RequestDispatcherExampleApp/s1/page2.jsp
Ex: 2
In request, http://localhost:8080/RequestDispatcherExampleApp/s1/s2/page1.jsp
Context root is /RequestDispatcherExampleApp
Relative path to request is /RequestDispatcherExampleApp/s1/s2/
So, request.getRequestDispatcher(“../page2.jsp”) while processing the request for
http://localhost:8080/RequestDispatcherExampleApp/s1/page1.jsp will look for page2.jsp under directory /RequestDispatcherExampleApp/s1/page2.jsp
From above example it is clear that request.getRequestDispatcher can process resource to the relative path of request URL.
Ex: 3
In request, http://localhost:8080/RequestDispatcherExampleApp/s1/s2/page1.jsp
Context root is /RequestDispatcherExampleApp
Relative path to request is /RequestDispatcherExampleApp/s1/s2/
So, request.getRequestDispatcher(“/page2.jsp”) while processing the request for
http://localhost:8080/RequestDispatcherExampleApp/s1/page1.jsp will look for page2.jsp under directory /RequestDispatcherExampleApp/
From above example it is clear that request.getRequestDispatcher can process resource to the relative path of context root of application.
2. servletContext.getRequestDispatcher(String path)
path should begin with ‘/’.
If the path does not start with ‘/’, you will get following exception
java.lang.IllegalArgumentException: Path does not start with a “/” character.
This can accept path relative to context root of the application.
In request,
http://localhost:8080/RequestDispatcherExampleApp/s2/page1.jsp
Context root is /RequestDispatcherExampleApp
Relative path to context root is /RequestDispatcherExampleApp/
So, servletContext.getRequestDispatcher(“/page2.jsp”) while processing the request for http://localhost:8080/RequestDispatcherExampleApp/s2/page1.jsp will look for page2.jsp under directory /RequestDispatcherExampleApp/page2.jsp
for Reference Please look into this:
Reply