Java servlets are making headlines these days, claiming to solve many of the problems associated with CGI and proprietary server API's. In this article Nakul describes the overall servlet architecture and what you need to develop a web application using servlets. He uses several coding examples to show you how to use the servlet API and compares it with CGI and proprietary server API's.
An Introduction to Java Servlets - ServletContext attributes (Page 8 of 10 )
All servlets belong to one servlet context. In version 1.0 and 2.0 of the servlet API, all servlets on one host belong to the same context, but with version 2.1 of the API, the context becomes more powerful and can be seen as the humble beginnings of an Application concept. Future versions of the API will make this even more apparent.
Many servlet engines implementing the Servlet 2.1 API let you group a set of servlets into one context and support more than one context on the same host. The ServletContext in the 2.1 API is responsible for the state of its servlets and knows about resources and attributes available to the servlets in the context. Here we will only look at how ServletContext attributes can be used to share information among a group of servlets.
There are three ServletContext methods dealing with context attributes: getAttribute, setAttribute and removeAttribute. In addition, the servlet engine may provide ways to configure a servlet context with initial attribute values. This serves as a welcome addition to the servlet initialization arguments for configuration information used by a group of servlets, for instance the database identifier we talked about above, a style sheet URL for an application, the name of a mail server, etc.
A servlet gets a reference to its ServletContext object through the ServletConfig object. The HttpServlet actually provides a convenient method (through its superclass, GenericServlet) named getServletContext to make it really easy:
The code above could be part of an application configuration servlet, processing the request from an HTML FORM where a new style sheet can be specified for the application. All servlets in the application that generate HTML can then use the style sheet attribute like this: