Chapter 11. Interservlet Communication

Servlets running together in the same server have several ways to communicate with each other. There are three major reasons to use interservlet communication:

Direct servlet manipulation

A servlet can gain access to the other currently loaded servlets and perform some task on each. The servlet could, for example, periodically ask every servlet to write its state to disk to protect against server crashes.

Servlet reuse

One servlet can use another’s abilities to perform a task. Think back to the ChatServlet from the previous chapter. It was written as a server for chat applets, but it could be reused (unchanged) by another servlet that needed to support an HTML-based chat interface.

Servlet collaboration

The most common, situation involves two or more servlets sharing state information. For example, a set of servlets managing an online store could share the store’s product inventory count. Session tracking (see Chapter 7 ) is a special case of servlet collaboration.

This chapter discusses why interservlet communication is useful and how it can be accomplished.

Servlet Manipulation

Direct servlet manipulation involves one servlet accessing the loaded servlets on its server and optionally performing some task on one or more of them. A servlet obtains information about other servlets through the ServletContext object. Use getServlet() to get a particular servlet:

public Servlet ServletContext.getServlet(String name) throws ServletException

This ...

Get Java Servlet Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.