top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How do I call one servlet from another servlet?please explain with example?

+1 vote
35 views
How do I call one servlet from another servlet?please explain with example?
posted Sep 29, 2015 by Shyam

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

+1 vote
 
Best answer

[ Short answer: there are several ways to do this, including
use a RequestDispatcher
use a URLConnection or HTTPClient
send a redirect
call getServletContext().getServlet(name) (deprecated, doesn’t work in 2.1+)
– Alex ]
It depends on what you mean by “call” and what it is you seek to do and why you seek to do it.
If the end result needed is to invoke the methods then the simplest mechanism would be to treat the servlet like any java object , create an instance and call the mehods.
If the idea is to call the service method from the service method of another servlet, AKA forwarding the request, you could use the RequestDispatcher object.
If, however, you want to gain access to the instance of the servlet that has been loaded into memory by the servlet engine, you have to know the alias of the servlet. (How it is defined depends on the engine.) For example, to invoke a servlet in JSDK a servlet can be named by the property

myname.code=com.sameer.servlets.MyServlet

The code below shows how this named servlet can be accessed in the service method of another servlet

   public void service (HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
              MyServlet ms=(MyServlet) getServletConfig().getServletContext().getServlet("myname");
           }

That said, This whole apporach of accessing servlets in another servlets has been deprecated in the 2.1 version of the servlet API due to the security issues. The cleaner and better apporach is to just avoid accessing other servlets directly and use the RequestDispatcher instead

answer Oct 1, 2015 by Karthick.c
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...