Edit Edit

Java Servlet FAQ


How can you call the public methods of a servlet from within a servlet?


Use ServletContext's getServlet() to get an instance of the specified servlet:

public Servlet getServlet(String name)

where name is the registered name or class name of the servlet. Then cast the return value of getServlet() into the Servlet subclass and call the desired method in that class.

getServlet() may return null if the servlet is not loaded yet. You can force the servlet to be loaded by making an HTTP request to the servlet via sockets. The following code is based on the sample code from Java Servlet Programming:

void loadServlet(String name, HttpServletRequest req)
{
    // open a socket to the Web server
    Socket socket = new Socket(req.getServerName(), req.getServerPort());

    // set the timeout to 4 seconds
    socket.setSoTimeout(4000);

    // send a GET request to the servlet to force the Web server to load the servlet
    PrinterWriter out = new PrintWriter(socket.getOutputStream(), true);
    out.println("GET /servlet/" + name + "HTTP/1.0");
    out.println();
    try {
        socket.getInputStream().read());
    }
    catch (InterruptedIOException e) {
        // do nothing
    }
    finally {
        out.close();
    }
}

public Servlet getServlet(String name, HttpServletRequest req, ServletContext context)
{
    // try getting an instance of the servlet
    Servlet servlet = context.getServlet(name);
    if (servlet != null)
        return servlet;

    // the servlet isn't loaded yet.  try loading it
    loadServlet(name, req);

    // try getting an instance of the servlet again
    return context.getServlet(name);
}

Now, in your servlet's doGet() method, you can call the above getServlet():

public void doGet(HttpServletRequest req, HttpServletResponse res)
                  throws ServletException, IOException
{
    // get an instance of MyServlet
    MyServlet myservlet = (MyServlet) getServlet("MyServlet", req, getServletContext());

    // call the public foobar() method in MyServlet
    myservlet.foobar();  
}



Last updated 12/27/1999 08:56:13 PM