Accessing init parameter

Expression Language helps us to get easier the init context parameters. These are parameters that are not servlet specific, but an application-wide available.

First thing, we should put a parameter in the web.xml. Here is my Deployment Descriptor (DD) file with the definition of the param-name:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">
    <context-param>
        <param-name>emailAddr</param-name>
        <param-value>my@email.address</param-value>
    </context-param>
</web-app>
We already know how to read that parameter in a servlet, going through the servlet context:
System.out.println(this.getServletContext().getInitParameter("emailAddr"));
and we know how to do the same in a JSP page using the implicit application object:
email is: <%= application.getInitParameter("emailAddr") %>
With the Expression Language it is even easier:
email is: ${initParam.emailAddr}
Actually, the name used as EL implicit object, initParam, is a bit misleading, since it is used for accessing the context-param elements. But, well, we have to bite the bullet and use it as it is.

I firstly wrote this post as a comprehension exercise while reading the eighth chapter of Head First Servlet and JSP, it's a good book to read if you are interested in this stuff.

No comments:

Post a Comment