Link to home
Start Free TrialLog in
Avatar of Java_Problem
Java_Problem

asked on

Difference between getRequestDispatcher () of ServletContext and ServletRequest

What is the difference between getRequestDispatcher () of ServletContext and ServletRequest

Please explain in easy to understand language and explain with a simple working example.

Please explain from latest J2EE version.

I want to understand when to use ServletContext and when to use ServletRequest's dispatcher call
SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sudhakar_koundinya
sudhakar_koundinya

ServletA
doPost{}{
RequestDispatcher showDispatcher = req.getRequestDispatcher("fwdinclude");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
showDispatcher.forward(req,resp);
}

Final url on your browser is http://localhost:8080/servlet/A

ServletA
doPost{}{
RequestDispatcher showDispatcher = req.getRequestDispatcher("fwdinclude");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
showDispatcher.include(req,resp);
}

Final url  on  your browser is http://localhost:8080/servlet/A

ServletA
doPost{}{

resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
res.sendRedirect("fwdinclude");
}

Final url is http://localhost:8080/servlet/fwdinclude
From the javadoc of ServletRequest.getRequestDispatcher(String):

'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(String) is that this method can take
a relative path.'

So, if you get your RequestDispatcher from the request, you don't need
the leading "/".