The solution to the java.lang.NullPointerException (null pointer) exception in the Servlet using getServletContext() to obtain the ServletContext object

Today, I encountered a java.lang.NullPointerException (null pointer) exception in the service method of the servlet to obtain the ServletContext object. The code is as follows

//Get the ServletContext object
 ServletContext servletContext = this.getServletContext();

  This problem is very strange, and it is the first time I encountered it, because it was written like this when I used to get the ServletContext object in the servlet's doGet/doPost methods, and there was no java.lang.NullPointerException (null pointer) exception. Check it online. The reason for this exception: it turned out that I rewrote the init(ServletConfig) method, but super.init(config) was not called inside the rewritten init method; that's what caused the error! The init (ServletConfig) of the parent class handles the reference to obtain the ServletContext object. Only in the doGet/doPost/service method can the SeverletContext object be obtained through the getServletContext() method! After rewriting the init method of the servlet, you must remember to call the init method of the parent class, otherwise a java.lang.NullPointerException will occur when you use the getServletContext() method in the service/doGet/doPost method to obtain the ServletContext object

public void init(ServletConfig config) throws ServletException{
    //After rewriting the init method of the Servlet, you must remember to call the init method of the parent class, otherwise a java.lang.NullPointerException will occur when you use the getServletContext() method in the service/doGet/doPost method to obtain the ServletContext object
  super.init(config);
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325249907&siteId=291194637