Servlet init parameters

The servlet context is a good place where storing constants that should be available to a servlet, if we want to be allowed to modify them without being forced to recompile the servlet code.

We just have do put them in the init-param section of our servlet, as defined in the web application Deployment Descriptor (DD), web.xml.

The nuisance of this approach is that a change in the DD still requires a restart of the Web Container (actually, if we are playing with an evoluted Web Container, there are way to do hot-redeploy - in any case, it's still a nuisance). An alternative would be storing the constants somewhere else, usually in a database. In this way we won't impact anymore on the container life, but we'll make a bit more complex the servlet code.

To store our servlet init parameter, we add them to our servlet section in the DD, in this way:
<servlet>
    <servlet-name>Beer Selector</servlet-name>
    <servlet-class>ch03.BeerSelector</servlet-class>
    <init-param>
        <param-name>adminEmail</param-name>
        <param-value>likewecare@wickedlysmart.com</param-value>
    </init-param>
    <init-param>
        <param-name>mainEmail</param-name>
        <param-value>blooper@wickedlysmart.com</param-value>
    </init-param>
</servlet>
Now we have an adminEmail and a mainEmail address available to our servlet. But remember that the servlet has no access to the its ServletConfig object at construction time, it should wait, at least, till its init() method is called. If we wanted to set servlet member variable, we should have redefined the init() method and did there the job.

To loop all over the servlet init parameters we'll do something like this:
Enumeration<String> descr = getServletConfig().getInitParameterNames();
while(descr.hasMoreElements()) {
    String email = getServletConfig().getInitParameter(descr.nextElement());
    // ...
}
The names of the parameters stored in the servlet init configuration are retrieved by a call to getInitParameterNames(), that returns a String Enumeration.

When we know the name of the init parameter we want to retrieve, we can call the getInitParameter() for it on the servlet config object.

I originally wrote this post while I was reading the fifth chapter of Head First Servlet and JSP, a fun ad interesting book on Java EE.

No comments:

Post a Comment