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

Source: Internet
Author: User

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

Related Article

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.