Difference between ServletRequest.getRequestDispatcher and ServletContext.getRequestDispatcher

October 26, 2011 | Programming

Servlet

If you use ServletRequest.getRequestDispatcher: you can use absolute path like “/index.jsp“, which forwards request to “http://www.myapp.com/index.jsp” from the request received directory

or you can use relative path like “index.jsp”, which forwards request to “index.jsp” which is relative to the request received servlet.
For example, if you receive your request on “http://www.myapp.com/mymodule/”,

RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
requestDispatcher.forward(request, response);

will forward the request to http://myapp.com/mymodule/index.jsp

If you use ServletContext.getRequestDispatcher: you must use absolute path like “/index.jsp“, which starts from application root folder (forwards to “http://www.myapp.com/index.jsp”)

For Example, if you receive your request on “http://myapp.com/mymodule/”,

RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/index.jsp");
requestDispatcher.forward(request, response);

will forward the request to “http://www.myapp.com/index.jsp”

Relative paths are not allowed here.

Tags: , ,

Leave a Reply

If you have a Tip, Comment, Article or anything you want to share, please send it to: i@poisure.com