With out looking at the HttpServlet source to confirm i would guess that:
In servlet 2 the member variable basepath is assigned a value after the
super class (HttpServlet) constructor returns but before the servlets
init(...) method is called by the servlet container. Therefore at the time
of assignment the servlet context is not set on the servlet and a NPE
results. That would be my guess.
Override init(...) call super.init(...) and then assign the value to
basepath.

Jon

-----Original Message-----
From: Mike Millson [mailto:[EMAIL PROTECTED]]
Sent: 08 June 2002 14:55
To: Tomcat Users List
Subject: context param is null outside doGet


Why is it that context parameters are null outside the doGet block of a
servlet?

For example, suppose I have the following in web.xml:

<context-param>
        <param-name>basepath</param-name>
        <param-value>bob</param-value>
</context-param>

Why does Servlet 1 below print out "bob" while Sevlet 2 gives me a
NullPointerException error? Why isn't the context parameter available
outside the doGet block?

Servlet 1
==========
public class Hello extends HttpServlet{

        public void doGet(HttpServletRequest request HttpServletResponse response)
                throws IOException, ServletException{

                PrintWriter out = response.getWriter();
                out.println(getServletContext()getInitParameter("basepath"));
                out.close();
        }
}

Servlet 2
==========
public class Hello extends HttpServlet{

        private String basepath = getServletContext()getInitParameter("basepath");

        public void doGet(HttpServletRequest request HttpServletResponse response)
                throws IOException, ServletException{

                PrintWriter out = response.getWriter();
                out.println(basepath);
                out.close();
        }
}

Thank you,
Mike


--
To unsubscribe, e-mail:
<mailto:[EMAIL PROTECTED]>
For additional commands, e-mail:
<mailto:[EMAIL PROTECTED]>



--
To unsubscribe, e-mail:   <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>

Reply via email to