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

Introduction

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.

Tip

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

Problem

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

Solution

Bind an object to ...

Get Java Servlet & JSP Cookbook 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.