O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Remember the difference between servlet init parameters and context init parameters

Here’s a review of the key differences between context init parameters and servlet init parameters. Pay special attention to the fact that they’re both referred to as init parameters, even though only servlet init parameters have the word “init” in the DD configuration.

Context init parameters

Servlet init parameters

Deployment Descriptor

Within the <web-app> element but NOT within a specific <servlet> element

<web-app ...>
  <context-param>
    <param-name>foo</param-name>
    <param-value>bar</param-value>
  </context-param>

  <!-- other stuff including
    servlet declarations -->
</web-app>

Note

Notice it doesn’t say “init” anywhere in the DD for context init parameters, the way it does for servlet init parameters.

Within the <servlet> element for each specific servlet

<servlet>
  <servlet-name>
     BeerParamTests
  </servlet-name>
  <servlet-class>
     TestInitParams
  </servlet-class>
  <init-param>
    <param-name>foo</param-name>
    <param-value>bar</param-value>
  </init-param>

  <!-- other stuff -->
</servlet>

Servlet Code

getServletContext().getInitParameter("foo");
getServletConfig().getInitParameter("foo");

Note

It’s the same method name!

Availability

To any servlets and JSPs that are part of this web app.

To only the servlet for which the <init-param> was configured.

 

(Although the servlet can choose to make it more widely available by storing it in an attribute.)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required