Mark Foster wrote:
> I think that example may only work for JSDK >= 2.1
> Using JSDK 2.0 here is what I do...
>
> servletobj s = (servletobj)getServletContext().getServlet("servletobj");
> String foo = s.someMethod().toString();
>
> It's too bad getServlet() was deprecated, because the technique described
> below seems alot more clunky.
> -mdf
>
I disagree (about the deprecation being "too bad").
The fact that a developer feels the need to call a method of another servlet
indicates that he or she is using servlets for the wrong purpose. Servlets are
designed to respond to requests, not be general purpose data storage or logic
components.
If you need to share data or logic beyond the lifetime of a particular request,
that data or logic should be placed in a separate Java class, and stored in the
appropriate scope (ServletContext.setAttribute() for things that are global to
an application, or HttpSession.setAttribute() for things that are specific to a
particular user session). Separation of function into specific classes is a
fundamental principle of good object oriented design that is being violated by
the code example above.
Craig McClanahan
>
> -----Original Message-----
> From: Ernie V [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, February 16, 2000 6:43 AM
> To: [EMAIL PROTECTED]
> Subject: Re: How can i call a servlet method from another servlet
>
> To call a servlet from another servlet, you need to get a reference to the
> servlet that you want to call by using the ServletContext. The servlet that
> you want to call from other servlets must put a reference to itself in the
> servlet context. Use getAttribute() and getAttribute() methods to accomplish
> this. This is usually done in the init() method of the callable servlet:
> public void init(ServletConfig cfg) throws ServletException
> {
> super.init(cfg);
> // Add this servlet to the context
> getServletContext().setAttribute("callableServlet", this);
> }
> Then put this in the calling servlet:
> CallableServlet cs =
> (CallableServlet)getServletContext().getAttribute("callableServlet");
> Now you can use the reference "cs" to invoke methods in the callable
> servlet.
> -ernie
>
> ___________________________________________________________________________
> To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
> of the message "signoff SERVLET-INTEREST".
>
> Archives: http://archives.java.sun.com/archives/servlet-interest.html
> Resources: http://java.sun.com/products/servlet/external-resources.html
> LISTSERV Help: http://www.lsoft.com/manuals/user/user.html
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html