getServletContext()獲取ServletContext對象出現NullPointerException的解決辦法

今天遇到了一個在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);
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章