request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.
In Java Servlet programming, both request.getRequestDispatcher()
and context.getRequestDispatcher()
are used to obtain a RequestDispatcher
object, but they differ in the way they determine the resource (i.e., servlet or JSP page) to which the request should be forwarded.
request.getRequestDispatcher(String path)
:- This method takes a relative path as an argument, which is interpreted relative to the current request’s path.
- For example, if the current request URL is “/example/currentServlet”, and you provide “somePage.jsp” as the path argument, it will look for “somePage.jsp” relative to the current URL.
javaRequestDispatcher dispatcher = request.getRequestDispatcher("somePage.jsp");
dispatcher.forward(request, response);
context.getRequestDispatcher(String path)
:- This method also takes a relative path, but it is interpreted relative to the context root of the web application.
- The context root is the base directory of your web application. For example, if your web application is deployed at “http://localhost/myWebApp“, and you provide “/somePage.jsp” as the path argument, it will look for “somePage.jsp” relative to the context root.
javaRequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/somePage.jsp");
dispatcher.forward(request, response);
In summary:
- Use
request.getRequestDispatcher()
when you want to specify the resource relative to the current request. - Use
context.getRequestDispatcher()
when you want to specify the resource relative to the context root of the web application.
Keep in mind that the usage depends on the specific requirements of your application and the location of the resource you want to forward the request to.