JSP servlet init parameters

Creating init parameters for a servlet is easy, when we need to do that for a JSP page it is only a bit more trickier, and we should remember a couple of details.

We can't use annotations, since the translation from JSP to servlet is not in our control. So we have to fall back to the Deployment Descriptor (DD). So, let's go in our web app WEB-INF directory and modify (maybe create) the web.xml file.

In the web-app element we need to create two elements, a servlet and a servlet-mapping, and in the servlet one we could create any init-param we need, just like we can do for a plain servlet.

Here is an example for a servlet element, based on a JSP page named counting.jsp placed in the web app root directory:
<servlet>
  <servlet-name>Counting</servlet-name>
  <jsp-file>/counting.jsp</jsp-file>
  <init-param>
      <param-name>base</param-name>
      <param-value>42</param-value>
  </init-param>
</servlet>
Notice the jsp-file element, that replaces what in a plain servlet is a servlet-class.

Then we need a servlet-mapping element, that should look something like this one:
<servlet-mapping>
  <servlet-name>Counting</servlet-name>
  <url-pattern>/counting.jsp</url-pattern>
</servlet-mapping>

And that's it. Now we can access that init parameter from our Counting JSP page.

For instance, we could be interested in accessing it when the JSP is initialized. In this case, we would override the jspInit() method and get it through getServletConfig(). Like this:
<%!
public void jspInit() {
    log("Config init param: " + getServletConfig().getInitParameter("base"));
}
%>
If we want to access it from a scriplet, we use the config implicit object:
<%= config.getInitParameter("base") %>

No comments:

Post a Comment