Return to Servlet index

Sharing Resources Among Servlets

 

Servlets running in the same server can share resources. This is especially useful when servlets combine to form a single application, as the Duke's Bookstore servlets do. Servlets in the same server can share resources using the ServletContext interface's methods for manipulating attributes: setAttribute, getAttribute, and removeAttribute.

All servlets in the same context share the attributes stored using the ServletContext. To avoid collisions of attribute names, one can name attributes using the same conventions as package names.

The following example shows a CatalogServlet getting the value of an attribute during the servlet's initialization. If the bookDBFrontEnd object does not already exist, a new one is created and stored in the servlet context:

public class CatalogServlet extends HttpServlet {

ServletConfig config;

public void init(ServletConfig config) throws ServletException {

this.config=config;

Object object = config.getServletContext().getAttribute("BookDBFrontEnd");

BookDBFrontEnd bookDBFrontEnd = null;

if (object != null) {

bookDBFrontEnd = (BookDBFrontEnd)object;

}

if (bookDBFrontEnd == null) {

config.getServletContext().setAttribute

("BookDBFrontEnd", BookDBFrontEnd.instance());

}

}

...

}

 

The 'Duke's Book Store' example project is a good illustration of the use of ServletContext attributes.

 

Return to Servlet index