ServletConfig vs ServletContext

ServletConfig vs ServletContext

After knowing fully of ServletConfig and ServletContext with examples, explanation and screen outputs, it is time to compare them for still better understanding.

ServletConfig vs ServletContext: Following table summarizes the differences between the two.

S.No. ServletConfig ServletContext
1 Defined in javax.servlet package. Defined in the same javax.servlet package.
2 Values are placed in web.xml file. Placed in the same web.xml file.
3 getInitParameter() defined ServletConfig is used to read values. Same method getInitParameter() is also present in ServletContext interface also to read the values.
4 When the values of <param-value> are changed, the Servlet need not be compiled again and thereby maintenance of code is easier. The same case also with <context-param>.
5 No limit on the existence of <init-param> tags in <servlet>. The same case here also, the web.xml fiel can have any number of <context-param> tags.
6 Servlet is initialized with the initialization data provided in <init-param>. This data is specific for one Servlet only. The data provided in <context-param> tag is meant for the usage of all Servlets under execution.
7 Data in included within <servlet> tag. Data is included within <context-param> tag.
8 It is local data for a particular Servlet. It is global data sharable by all servlets.
9 Each Servlet comes with a separate ServletConfig object. There will be only one ServletContext object available accessed by all Servlets.

Realtime examples on ServletConfig vs ServletContext:

  1. ServletConfig: Suppose I would like to know the amount payable for the number of mangoes purchased. I read the number of mangoes from the client html file. Then, which is the better place to have the cost of mango placed? Moreover, the cost of mango changes everyday. May be database table. If it is placed in a database table, for reading it is required a JDBC program with an extra overhead of database connection. The best place is web.xml file which does not require compilation every time the mango cost changes. Here, the servlet can be initialized with mango cost by the time client sends the number of mangoes. But remember, this mango cost is readable by one servlet only because the mango cost is placed within the <servlet> tag.
  2. ServletContext: I take the same above scenario with different perspective. Imagine there are multiple fruit vendors (each fruit shop is represented by one Servlet) and all require the cost of one mango. That is, the mango cost should be global. The place to put the cost of mango is in which exists outside any <servlet> tag. As it is outside any <servlet> tag, every servlet under execution can access.

Pass your comments and suggestions on this tutorial ServletConfig vs ServletContext.

Leave a Reply

Your email address will not be published. Required fields are marked *