Alex Rivera | Logout

ServletConfig vs ServletContext

Asked 2010-11-19T09:19:50.947
60

What is the difference between ServletConfig and ServletContext interface?

Edit
Report

2 Answers

20

ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.

ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web application is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.

Source: http://javapapers.com/servlet/difference-between-servletconfig-and-servletcontext/

answered 2013-02-05T01:19:49.940
4

That's answered in the introducory text of their javadocs.

ServletConfig javadoc:

A servlet configuration object used by a servlet container to pass information to a servlet during initialization.

ServletContext javadoc:

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)

In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

The javadoc also contains a list of available methods along with explanation of their use. It gives a good overview of what's all available/possible with them.

answered 2010-11-19T12:53:13.333

Your Answer