June 07, 2011

How do I call one servlet from another servlet?

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.

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts