Context init parameters

We already know how to set and use the servlet init parameters. They are useful, if we want to have constants loaded at startup by the container, but they have a couple of issues that are addressed by the context init parameters.

Servlet init parameters are local to the servlet they refer to. So, JSP pages have no (easy) way to access them and they can't be shared among different servlets.

On the other side, context init parameters are accessible from all servlets and JSPs in the web application. If this is what you want, well, just go for it.

It's easy to define a context init parameter in the DD:
<web-app ... >
    <!-- -->

    <context-param>
        <param-name>adminEmail</param-name>
        <param-value>clientheaderror@wickedlysmart.com</param-value>
    </context-param>

    <!-- -->
</web-app>
And once the web application is loaded in the container, we can access it in any servlet and JSP.

Here we see a few lines that, once put in any method in any servlet in the web application, would put name and value to the output console for all the context init parameter:
ServletContext context = getServletContext();
Enumeration<String> names = context.getInitParameterNames();
while(names.hasMoreElements()) {
    String s = names.nextElement();
    System.out.print(s + ": ");
    String e = context.getInitParameter(s);
    System.out.println(e);
}
But remember you can't do that in a servlet constructor. You have to wait at least for the init() method to be called.

And we can do the same in all the web app's JSP pages:
<%
    Enumeration<String> names = getServletContext().getInitParameterNames();
    while(names.hasMoreElements()) {
        String name = names.nextElement();
        out.print(name + ": ");
        String value = getServletContext().getInitParameter(name);
        out.println(value + "<br />");
    }
%>
I wrote this post while reading the fifth chapter of Head First Servlet and JSP, a fun ad interesting book on Java EE.

No comments:

Post a Comment