Application settings when using servlets

I posted some notes a couple weeks ago about .NET configuration files, came across the code for doing the same thing in a servlet container tonight. Basically, you get a ServletConfig object using the getServletConfig() method of the Servlet interface and then call getInitParameter(String initParamName) on that. For example, let’s say that I put a global database connection string in my web.xml deployment descriptor:

<web-app>
  <servlet>
   <servlet-name>myservlet</servlet-name>
   <servlet-class>MyServlet</servlet-class>
    <init-param>
     <param-name>connection_string</param-name>
     <param-value>user id=sa;password=mypassword;initial catalog=mydb;data source=mydbserver;Connect Timeout=30</param-value>
    </init-param>
  </servlet>
</web-app>

Then, in my servlet code init() method, I could write this:

ServletConfig sc = getServletConfig();
String connection_string = sc.getInitParameter(“connection_string”);

After retrieving the value from the ServletConfig object, you’ll probably want to store it for later use in the ServletContext object:

ServletContext c = getServletContext();
c.setAttribute(“connection_string”, connection_string);

Now I can get the connection string in a JSP or a servlet later using this short snippet:

String myCS = (String)getServletContext().getAttribute(“connection_string”);

One thought on “Application settings when using servlets”

  1. Also note that in web.xml you can also define “environment entries” that apply across the entire servlet context, not just for an individual servlet. I think this might be a more appropriate place to put something like database connections.

    Here’s a sample from Tomcat 4.1’s “examples” web.xml:

    <env-entry>
      <env-entry-name>minExemptions</env-entry-name>
      <env-entry-value>1</env-entry-value>
      <env-entry-type>java.lang.Integer</env-entry-type>
    </env-entry>

Leave a Reply

Your email address will not be published. Required fields are marked *