文章出處
文章列表
今天遇到了一個在servlet的service方法中獲取ServletContext對象出現java.lang.NullPointerException(空指針)異常,代碼如下:
1 //獲取ServletContext對象 2 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異常
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 }
文章列表
全站熱搜