The ServletContext

 < Free Open Study > 

In a web container, each web application is associated with a context, and all resources contained within a web application exist relative to its context. A servlet context is rooted at a known path within a web container. For example if we have a store application, it could exist under the context /store. Therefore if the application contained an HTML file called home.html if would be accessible at http://localhost:8080/store/home.html. All requests that begin with the /store request path, known as the context path, are routed to the web application associated with the servlet context.

Each context that exists in a web container has a special object called a ServletContext associated with it. The ServletContext represents the web application's view on the container that it is deployed within. Everything that the web application is allowed to know about its container can be accessed via the ServletContext, and it allows servlets to access resources available to them in the container. The ServletContext can be thought of as a sandbox for a web application. This sandbox allows us to have all of the benefits of isolating web applications that we mentioned above (no name clashes, and efficient classloading without having to set a classpath).

The ServletContext can be used to accomplish many tasks in a web application. This said, perhaps the primary use of the ServletContext is to share attributes between all of the servlets in an application, and for loading resources for use within the application. We also define application initialization parameters using the ServletContext; we will discuss this later, in the section relating to deployment descriptors.

Defining Contexts within Tomcat

In order to create a context for your completed web application in Tomcat you only have to do one thing (and you don't always have to do that).

We can examine some of the contexts which exist within a freshly installed version of Tomcat 4.0 by looking in the file %CATALINA_HOME%/conf/server.xml. If you look towards the bottom of this file you will see a line like:

     <context path="/examples" docBase="examples" debug="0" reloadable="true"> 

This defines the context for the examples application provided with Tomcat 4.0. Later on, in the section about deploying our example application to Tomcat, we will discuss the many parameters that can be provided when defining contexts.

 < Free Open Study > 

Professional Java Servlets 2.3
Professional Java Servlets 2.3
ISBN: 186100561X
EAN: 2147483647
Year: 2006
Pages: 130

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: