在Servlet使用getServletContext()获取ServletContext对象出现java.lang.NullPointerException(空指针)异常的解决办法
程序员文章站
2022-04-16 08:53:55
...
今天在Servle的重写init方法中获取getServletContext()一直报java.lang.NullPointerException(空指针)异常。
public void init(ServletConfig config) throws ServletException {
List<User> list = new ArrayList<User>();
this.getServletContext().setAttribute("list", list);
}
上网查了一下出现这个异常的原因:原来是我重写了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 {
super.init(config);
List<User> list = new ArrayList<User>();
this.getServletContext().setAttribute("list", list);
}