標籤:
在Servlet使用getServletContext()擷取ServletContext對象出現java.lang.NullPointerException(null 指標)異常的解決辦法
今天遇到了一個在servlet的service方法中擷取ServletContext對象出現java.lang.NullPointerException(null 指標)異常,代碼如下:
1 //擷取ServletContext對象2 ServletContext servletContext = this.getServletContext();
這個問題很奇怪,也是第一次遇到,因為以前在servlet的doGet/doPost方法中要擷取ServletContext對象時都是這樣寫的,也沒有出現過java.lang.NullPointerException(null 指標)異常,上網查了一下出現這個異常的原因:原來是我重寫了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異常
1 public void init(ServletConfig config) throws ServletException{2 //重寫了Servlet的init方法後一定要記得調用父類的init方法,否則在service/doGet/doPost方法中使用getServletContext()方法擷取ServletContext對象時就會出現java.lang.NullPointerException異常3 super.init(config);4 }
在Servlet使用getServletContext()擷取ServletContext對象出現java.lang.NullPointerException(null 指標)異常的解決辦法