1

Trying to add init parameter names to a list in init(ServletConfig) method.

public void init(ServletConfig sc){
    try {
        super.init(sc);
        Enumeration<String> e= sc.getInitParameterNames();
        while(e.hasMoreElements()){
            list.add(e.nextElement());
        }
    } catch (ServletException e1) {
        e1.printStackTrace();
    }
}

I am getting a NullPointerException when I use this list because e.hasMoreElement() returns false. I am pretty sure that I have added the init parameters correctly in the web.xml file. What is going wrong? Please advice.

6
  • 1
    I think you are getting a NullPointerException because list is null.
    – Thilo
    Commented Jun 21, 2012 at 8:49
  • Thanks for the reply. I know the reason for the NullPointerException, my question is have I used the getInitParameters incorrectly such that e.hasMoreElements() returns false... Commented Jun 21, 2012 at 8:51
  • @NeloAngelo I don't think you understood that correctly: You probably get the NPE because list has not bee initialized (see Ramesh's answer below) - and not because you didn't add elements to it. BTW: How shall we tell if you used the init parameters correctly if you don't post the code where you set them?
    – hage
    Commented Jun 21, 2012 at 8:53
  • It is possible that hasMoreElements returns false the first time. Are you sure you have init parameters?
    – Thilo
    Commented Jun 21, 2012 at 8:54
  • I think sc.getInitParameterNames() is null, check your init params
    – Kushan
    Commented Jun 21, 2012 at 8:57

1 Answer 1

4

I think you have not intialized the list object. The list object is null.

Change the code list this:

public void init(ServletConfig sc){
   try {
      super.init(sc);
      list = new ArrrayList<String>();
      Enumeration<String> e= sc.getInitParameterNames();
      while(e.hasMoreElements()){
         list.add(e.nextElement());
      }
   } catch (ServletException e1) {
    e1.printStackTrace();
   }
}
2
  • Thanks for the reply. I have one more question. As I read from Head First Servlets that when we override init(ServletConfig) we must a call to super.init(ServletConfig). Is it true? And if it is then I have a little confusion coz my code wasn't generating any errors or exception without the call to super.init(ServletConfig) Commented Jun 21, 2012 at 8:55
  • super.init(ServletConfig) only initializes the servlet config member variable. And, you should face the problem only if you use getServletConfig() method which return the intialized method.
    – Ramesh PVK
    Commented Jun 21, 2012 at 9:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.