Chapter 16. Binding, Accessing, and Removing Attributes in Web Applications


An attribute is a Java object that servlet code can bind, or store, in a certain scope, such as a ServletContext, a session, or a request. The object can temporarily store and share a small piece of data in a way that is not otherwise available to servlet developers. Then, when the application no longer has use for the object, your code can remove, or unbind it, and the web container makes the object available for garbage collection.

This chapter describes how to work with attributes in all three scopes: ServletContext, session, and request. If you need to make an object available to all of the servlets and JSPs in a context, then you can bind the object to a ServletContext. If the application calls for an object such as a “shopping cart” to be bound to a session (see Chapter 11), you can set the object as a session attribute. Finally, if the application requires two servlets that communicate via a RequestDispatcher to share an object, then the servlets can use an object attribute bound to a request scope.


Since sessions and requests are associated with numerous users in a busy web application, developers have to pay attention to the size and resource use of any objects that are bound as attributes to requests or sessions.

16.1. Setting ServletContext Attributes in Servlets


You want to make an object available to all servlets in a context or web application.


Bind an object to ...

Get Java Servlet & JSP Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.