1. 程式人生 > >在Servlet使用getServletContext()獲取ServletContext對象出現java.lang.NullPointerException(空指針)異常的解決辦法

在Servlet使用getServletContext()獲取ServletContext對象出現java.lang.NullPointerException(空指針)異常的解決辦法

是我 沒有 AS pre 代碼 erl fig post exceptio

今天遇到了一個在servlet的service方法中獲取ServletContext對象出現java.lang.NullPointerException(空指針)異常,代碼如下

 //獲取ServletContext對象
 ServletContext servletContext = this.getServletContext();

  這個問題很奇怪,也是第一次遇到,因為以前在servlet的doGet/doPost方法中要獲取ServletContext對象時都是這樣寫的,也沒有出現過java.lang.NullPointerException(空指針)異常,上網查了一下出現這個異常的原因:原來是我重寫了init(ServletConfig)方法,但重寫的init方法內部沒有調用super.init(config);就是這導致了錯誤!父類的 init(ServletConfig)有處理獲取ServletContext對象的引用,在doGet/doPost/service方法方法中才能夠通過 getServletContext()方法獲取到SeverletContext對象!重寫了Servlet的init方法後一定要記得調用父類的init方法,否則在service/doGet/doPost方法中使用getServletContext()方法獲取ServletContext對象時就會出現java.lang.NullPointerException異常

 public void init(ServletConfig config) throws ServletException{
    //重寫了Servlet的init方法後一定要記得調用父類的init方法,否則在service/doGet/doPost方法中使用getServletContext()方法獲取ServletContext對象時就會出現java.lang.NullPointerException異常
  super.init(config);
}

  

在Servlet使用getServletContext()獲取ServletContext對象出現java.lang.NullPointerException(空指針)異常的解決辦法