Discussions

Web tier: servlets, JSP, Web frameworks: Application-wide parameters in web.xml

  1. Application-wide parameters in web.xml (1 messages)

    I've tried to put some application-wide parameters in my deployment descriptor such as database connection information. Looks like this:

    <web-app>
    <context-param>
    <param-name>dbDriverName</param-name>
    <param-value>org.gjt.mm.mysql.Driver</param-value>
    <description>This attribute defines the database driver being used</description>
    </context-param>

    ...
    </web-app>

    Isn't the right way to collect the data (in my example dbDriverName) to do something like this (after grabbing the servletConfig in the init(ServletConfig servletConfig) method of the servlet):

    ServletContext thisContext = servletConfig.getServletContext();
    dbDriverName = (String) thisContext.getAttribute("dbDriverName");

    This way, all I get is null. :-( Am I going the right way or am I missing something?

    Running Tomcat 3.3, BTW

    Thanks!


    Markus

  2. hey markus,

    you're on the right track, but you're just using the wrong method call. when you define context-param's in web.xml for you web applications, you retrive them using the 'getInitParameter(String param)' method.

    To quickly test it using JSP you can use:
    ----------------------------------------------------------
    <%= application.getInitParameter("dbDriverName") %>
    ----------------------------------------------------------

    From your code, you just need to modify the method:
    ----------------------------------------------------------
    ServletContext thisContext = servletConfig.getServletContext();

    // This method would work had you stored it with setAttribute at run time
    // dbDriverName = (String) thisContext.getAttribute("dbDriverName");

    // use this instead
    dbDriverName = thisContext.getInitParameter("dbDriverName");
    ----------------------------------------------------------


    Just think of it this way; it's an initial parameter and it will always be a String. getAttribute and setAttribute are usually used at run time to store objects within the servlet context.

    Hope this helps! =)

    oh yeah, i guess this confirms that JSP's implicit 'application' object is really the ServletContext object. I kind of knew, but never really confirmed until now, so thank you! =p