Workaround for use of Getservletcontext () in servlet to get ServletContext object java.lang.NullPointerException (null pointer) exception

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.