Today encountered a java.lang.NullPointerException (null pointer) exception in the Servlet service method that gets the ServletContext object, the code is as follows:
1 // get ServletContext Object 2 this. Getservletcontext ();
This is a very strange and first encounter, because it was written in the Doget/dopost method of the servlet, and did not appear in the previous ServletContext object java.lang.NullPointerException (null pointer) exception, the internet looked up the reason for this exception: it was I rewrote the init (ServletConfig) method, but the overridden Init method does not call Super.init (config); that's what caused the error! The parent class's Init (ServletConfig) has a reference to handle getting the ServletContext object, which can be passed Getservletcontext () in the Doget/dopost/service method method. Method gets the Severletcontext object! after overriding the Servlet's Init method, be sure to remember to call the parent class's Init method, otherwise the service/doget/ The java.lang.NullPointerException exception occurs when you get the ServletContext object using the Getservletcontext () method in the Dopost method
1 Public void throws servletexception{2 // after overriding the Servlet's Init method, be sure to recall calling the parent class's Init method, otherwise use Getservletcontext () in the Service/doget/dopost method The java.lang.NullPointerException exception 3Super. Init (config) occurs when the ServletContext object is fetched by the 4 }
Workaround for use of Getservletcontext () in servlet to get ServletContext object java.lang.NullPointerException (null pointer) exception