The Servlet API provides the class javax.servlet.ServletContext, which has methods that work with data stored in context. Any servlet can store Java objects in that context and other servlets can use them. The objects are stored with a String key for uniqueness.
Here’s how it works:
- Use setAttribute(String key, Object value) to store an attribute in context. key is the name of the attribute and value is the Java object to be stored.
- Use getAttribute(String key) to retreive the Java object corresponding to the value of key in context. If no object is found, null is returned.
- Remove attributes from context using remove(String key).
ServletContext can be used in other ways besides data sharing?for instance, working with RequestDispatcher or logging into the servlet log file.