Passing data from servlet to another servlet using RequestDispatcher
Asked Answered
C

2

6

I am trying to pass data from one servlet to another using the RequestDispatcher. This is my code for the Dispatcher.

String address;

address = "/Java Resources/src/coreservlets/MapOut.java";

RequestDispatcher dispatcher =
  request.getRequestDispatcher(address);
dispatcher.forward(request, response);

When I try to run it, it gives me an error saying the path is unavailable. Do I have to include something for the dispatcher to send to another servlet?

Chrystalchryste answered 12/7, 2012 at 17:30 Comment(0)
A
12

You just need to pass servlet-mapping 's url-pattern in the getRequestDispatcher.

Let say your servlet mapping is "myMap" for the "MapOut" Servlet in the web.xml.Then it should be

RequestDispatcher dispatcher = request.getRequestDispatcher("/myMap");
dispatcher.forward(request,response);

doGet() of forwarded Servlet will be called.

Example: web.xml

      <servlet>
        <description></description>
        <servlet-name>MapOut</servlet-name>
        <servlet-class>coreservlets.MapOut</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>MapOut</servlet-name>
        <url-pattern>/myMap</url-pattern> <!-- You can change this-->
      </servlet-mapping>
Atiana answered 13/7, 2012 at 4:48 Comment(5)
I am still a bit confused, what do you mean by servlet mapping.Chrystalchryste
RequestDispatcher rd; rd = request.getRequestDispatcher("/MapOut"); rd.forward(request, response); this is what i have on the servlet that I want the attributes created in to be forwarded to "\MapOut" ... do I have to make a request in the MapOut class?Chrystalchryste
Can we have a servlet without a mapping?Recollected
@HardikMishra I have a small question. Don't we need request.setAttribute() method by setting attribute to forward? And why don't we use that?Ez
@pippilongstocking : You can use that but here the question was about forwarding not on setting attributesAtiana
W
1

You can directly write your name of the servlet in request.getRequestDispatcher("your servlet name"); it will fetch the path according to the web.xml configuration.

RequestDispatcher rd= request.getRequestDispatcher("MyServletName");
rd.forward(request,response);
Wrote answered 12/2, 2014 at 10:53 Comment(3)
It is not working. plz let me in which version it is working..I am using servlet 2.4Milanmilanese
@saurabh yes. it's working in servlet version 2.4, please check the name of servlet and path.Wrote
This done via javax.servlet.ServletContext.getNamedDispatcher(String). request.getRequestDispatcher works only for pathsDey

© 2022 - 2024 — McMap. All rights reserved.