WelcomeTo
WelcomeTo

Reputation: 20571

getRequestDispatcher() to another context

How to redirect Request object using getRequestDispatcher(), which located in another context? Or how I can redirect data that stored inside Request object to another JSP? Mehod of HTTP protocol must be same (i.e. if initial method - POST, then i must redirect with POST. So sendRedirect() not applicable)

Upvotes: 1

Views: 3931

Answers (1)

Govind
Govind

Reputation: 449

The following is the way of setting the data in the Request object .And getting the Value in the another page by using request.getAttribute() method.The sample code is :

RequestDispatcher rd = request.getRequestDispatcher("newpage.jsp");
  request.setAttribute("msg","Welcome");
 rd.forward(request, response);

And It can also be used with ServletContext

  ServletContext context= getServletContext();
  RequestDispatcher rd= context.getRequestDispatcher("/LoggedIn");
  rd.forward(request, response);

I dont think that the method type must same.Its an object of type Request and it can be accessed within the Context.And the difference between SendRedirect and Forward is that

In forward()

  1. we pass request and response object so our old request object is present on new resource which is going to process our request.

2.It is accessed within the same server ,another resource could be any servlet, jsp page any kind of file.

In sendRedirect() :

1.client request to some other location,the new location is available on different server or different context.

2.It is visible in browser as a new request .It can also be called as the Client Redirect.

Upvotes: 3

Related Questions