tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <craig...@apache.org>
Subject Re: getServletConfig returning null
Date Sun, 16 Feb 2003 23:52:43 GMT


On Sun, 16 Feb 2003, Marc Chamberlin wrote:

> Date: Sun, 16 Feb 2003 14:33:12 -0800
> From: Marc Chamberlin <marcc@easystreet.com>
> Reply-To: Tomcat Users List <tomcat-user@jakarta.apache.org>
> To: Tomcat Users List <tomcat-user@jakarta.apache.org>
> Subject: getServletConfig returning null
>
> Hello
> I am trying to understand how servlet configuration and initialization parameters work
and am running into a difficulty in Tomcat
> Version 4.1.18  I have the following configuration in in web.xml file -
>
> <servlet>
> <servlet-name>StarChartServlet</servlet-name>
> <servlet-class>starchart.StarChartServlet</servlet-class>
> <init-param>
> <param-name>starChartWorkingDirectory</param-name>
> <param-value>C:\temp\</param-value>
> </init-param>
> </servlet>
>
> In the servlets init method, I have the following code:
>
> try {
> starChartWorkingDirectory = getServletConfig().getInitParameter("starChartWorkingDirectory");
> } catch (java.lang.Exception ie) {
> System.out.println("Init Exception = " + ie.toString());
> }
>
> and I am getting a null pointer exception thrown here...  Nothing else appears to be
wrong in the log files and the servlet does
> function except for this issue.  Any help and guidance would be much appreciated! Thanks...
>

The simplest way to cause this problem is to mess up your
init(ServletConfig) method, and forget to call super.init(config) before
calling getServletConfig():

  public void init(ServletConfig config) throws ServletException {
    ... do some stuff but ...
    ... do not call super.init(config) ...
    String foo = getServletConfig().getInitParameter("foo"); // NPE
    super.init(config);
    String bar = getServletConfig().getInitParameter("bar"); // Works
  }

The superclass init() method is where a pointer to the initial
ServletConfig object gets saved, so that getServletConfig() can find it.

To avoid ever embarassing yourself with this mistake (trust me, nearly
everyone who programs servlets makes it at least once :-), you should
change your servlets to use the no-args version of init():

  public void init() throws ServletException {
    ... do some stuff ...
  }

because the container will call the init(ServletConfig) method in the base
class, which will in turn call your init() method -- no risk of forgetting
the superclass call.

>      Marc...
>

Craig

---------------------------------------------------------------------
To unsubscribe, e-mail: tomcat-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: tomcat-user-help@jakarta.apache.org


Mime
View raw message