我的问题是这样的:
有一个servlet用于在tomcat启动时从数据库中取得一些数据,放在ServletContext中,tomcat启动时没有问题,问题在于,当我在启动后再一次调用这个servlet的时候,就抛出“空指针”的例外,不知道为什么。我的serlvet程序是这样的
public class InitCrWay extends HttpServlet{
   public void init(){
      this.initway();   
   }   public void initway(){
      String[] wayCodeList;
      String[] wayNameList;
      ServletContext ctx = null;
      ctx = this.getServletContext();        CrccomcustBO wayBO = new CrccomcustBO();
        ArrayList wayList = new ArrayList();
        wayList = wayBO.searchWay("00","");
        if(wayList!=null && wayList.size()!=0){
          int count = wayList.size();
          wayCodeList = new String[count];
          wayNameList = new String[count];
          for(int i=0;i<count;i++){
             Crccomcust way = (Crccomcust)wayList.get(i);
             wayCodeList[i] = way.getCkind();
             wayNameList[i] = way.getCkindvalue();
          }          if((ctx.getAttribute("wayCodeList")!=null)||(ctx.getAttribute("wayNameList")!=null)){
               ctx.removeAttribute("wayCodeList");
               ctx.removeAttribute("wayNameList");
          }
          ctx.setAttribute("wayCodeList",wayCodeList);
          ctx.setAttribute("wayNameList",wayNameList);
System.out.println("成功取得所属行业表!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        }   }
}
启动后在别的类中调用该方法是
InitCrWay icw = new InitCrWay();
icw.initway();

解决方案 »

  1.   

    对了,错误提示是这样的:
    java.lang.NullPointerException
            at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:15
    9)
            at app.creditmanage.InitCrWay.initway(InitCrWay.java:23)
      

  2.   

    那servlet是怎么用的啊?
    我是想在tomcat启动的时候从数据库取出一些数据,放在ServletContext中,这是可以的。问题是,当我需要的数据发生改变时,我想及时更新保存在ServletContext中的数据,请问我这样用ServletContext不可以吗?那应该怎么用呢?或者说我应该怎么实现我这个功能。因为这些数据是所用访问该应用都用到的,而且我不想每次用到都访问一回数据库,这样效率比较低。
      

  3.   

    Servlet在web.xml中配置,不是让你去生成servlet的实例,容器会帮你生成,赶紧补课吧呵呵.
      

  4.   

    你可以在另一个servlet中修改ServletContext的数据啊
      

  5.   

    是不是因为servlet是多线程的 ServletContext ctx没做线程同步处理
      

  6.   

    还是不行啊,请教infowain(infowain) 如何编写这个单例模式啊?
      

  7.   

    public class Singleton {
      private Singleton(){}
      //注意这是private 只供内部调用
      private static Singleton instance = new Singleton();
      //这里提供了一个供外部访问本class的静态方法,可以直接访问  
      public static Singleton getInstance() {
        return instance;   
       } 
    }
      

  8.   

    小弟有点愚,麻烦redsun1209(红日) 能否详细告知如何使用该类。还有我觉得这种单例模式好像不能解决我的问题啊,我是想当客户修改了信息后,及时更新保存在ServletContext中的信息,如果是单例模式,好像是这个实例只能实例化一次,不能再实例化了?还请各位大哥指教。
      

  9.   

    晕,第一次有人servlet这样写。强。
    InitCrWay icw = new InitCrWay();
    icw.initway();
    应该在web.xml文件里配置的,不是new出来的。
      

  10.   

    还得请教redsun1209(红日) 大哥,具体怎么设计这个类啊!谢谢