Workaround for use of Getservletcontext () in servlet to get ServletContext object java.lang.NullPointerException (null pointer) exception
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 ServletContext ServletContext = This.getservletcontext ();
This is a very strange and first-time encounter, because it was written in the servlet's Doget/dopost method to get the ServletContext object, nor did it appear 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 recall calling the parent class's Init method, otherwise use Getservletcontext () in the Service/doget/dopost method The java.lang.NullPointerException exception occurs when the ServletContext object is fetched by the
1 public void init (ServletConfig config) throws servletexception{2 //rewrite the servlet's Init method and remember to call the parent class's Init method. Otherwise, the java.lang.NullPointerException exception occurs when you get the ServletContext object using the Getservletcontext () method in the Service/doget/dopost Method 3 Super.init (config); 4}
Workaround for use of Getservletcontext () in servlet to get ServletContext object java.lang.NullPointerException (null pointer) exception