Servlet Collaboration

Sometimes servlets have to cooperate, usually by sharing some information. We call communication of this sort servlet collaboration. Collaborating servlets can pass the shared information directly from one servlet to another through method invocations, as shown earlier. This approach requires each servlet to know the other servlets with which it is collaborating—an unnecessary burden. There are several better techniques.

Collaboration Through the System Properties List

One simple way for servlets to share information is by using Java’s system-wide Properties list, found in the java.lang.System class. This Properties list holds the standard system properties, such as java.version and path.separator, but it can also hold application-specific properties. Servlets can use the properties list to hold the information they need to share. A servlet can add (or change) a property by calling:

System.getProperties().put("key", "value");

That servlet, or another servlet running in the same JVM, can later get the value of the property by calling:

String value = System.getProperty("key");

The property can be removed by calling:

System.getProperties().remove("key");

It’s best if the key for a property includes a prefix that contains the name of the servlet’s package and the name of the collaboration group. For example, "com.oreilly.servlet.ShoppingCart".

The Properties class is intended to be String based, meaning that each key and value is supposed to be a String. This limitation, ...

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.