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:
...
ServletContext context = getServletContext();
String styleSheet = request.getParameter("stylesheet");
if (styleSheet != null) {
// Specify a new style sheet for the application
context.setAttribute("stylesheet", styleSheet);
}
...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:
...
ServletContext context = getServletContext();
String styleSheet = context.getAttribute("stylesheet");
out.println("<HTML><HEAD>");
out.println("<LINK HREF=" + styleSheet + " TYPE=text/css REL=STYLESHEET>");
...Next: Request attributes and resources >>
More Java Articles
More By Nakul Goyal