Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequestDispatcher from servletcontext versus request

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”);
like image 244
mohsen.nour Avatar asked Nov 13 '14 17:11

mohsen.nour


People also ask

What are the two methods of RequestDispatcher interface?

The RequestDispatcher interface provides two methods. They are: public void forward(ServletRequest request,ServletResponse response)throws ServletException,java. io.

Why use RequestDispatcher to forward a request to another resource instead of SendRedirect?

We can use request dispatcher only when the other servlet to which the request is being forwarded lies in the same application. On the other hand Send Redirect can be used in both the cases if the two servlets resides in a same application or in different applications.

What is the difference between doing and include or a forward with a RequestDispatcher?

The key difference between the two is the fact that the forward method will close the output stream after it has been invoked, whereas the include method leaves the output stream open. Junior developers often get confused between the include and the forward methods of the RequestDispatcher.


1 Answers

1) RequestDispatcher view = request.getRequestDispatcher(“result.jsp”);

Here,

  • view is relative to the current request. you have to pass relative path of jsp/html
  • for chaining two Servlets with in the same web application.

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,

  • view is relative to the root of the Servlet context, you have to pass absolute path of jsp/html
  • for chaining two web applications with in the same/different servers.

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.

like image 63
Abhishek Nayak Avatar answered Oct 29 '22 17:10

Abhishek Nayak