Don't make that pass! Passing initialization parameters between servlets (5/20/99)

The JavaWorld experts answer your most pressing Java questions -- every week

Q: I have problems when I call one servlet from another. I want to pass servlet initialization parameters through the calling servlet. I invoke the servlet through javax.servlet.servletContext.getServlet("name"). The javadocs, however, say this is dangerous. Why? Is there a better way?

A: First of all, the Servlet API does not provide a way for some servlet (call it Source) to specify initialization parameters for some other servlet (Target). What would happen if Target were called before Source?

Target should have its own initialization parameters specified through the servlet engine. If it needs information from Source, then it should have setX() methods that Source can call.

Secondly, how should Source get a reference to Target in the first place? ServletContext.getServlet() is a dangerous method. For one thing, it takes control away from the servlet engine. Once Source has a reference to Target, for example, the servlet engine will not be able to shut down or restart Target without worrying that Source is still using it. Moreover, the getServlet() method is a security risk. For instance, if Target has a JDBC Connection object for a sensitive database, then Source might be able to make mischief by calling Target's methods and using its fields directly.

Version 2.1 of the Servlet API addresses this issue with the RequestDispatcher interface. Until your servlet engine supports 2.1, though, you won't be able to use RequestDispatcher. Since I don't know exactly what you are trying to do, I cannot recommend a specific alternative. I can suggest that you find out if your servlet engine supports features like chaining, JavaServer Pages, or Server Side Include with servlets.

Learn more about this topic