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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access