About the MyEclipse servlet called This.getservletcontext (). Getrealpath () throws an exception that is null

Source: Internet
Author: User

Problem Description:

A null pointer exception was thrown when calling new FileInputStream (This.getservletcontext (). Getrealpath (1.png)) when displaying Web App directory slice 1.png:

Critical: Servlet.service () for Servlets [Downloadservlet] in context with path [/servlet] threw exception
Java.lang.NullPointerException

Workaround: After repeatedly determining the code input and path Normal, find this solution Servletcontext.getrealpath (), here to explain the personal understanding:

The implementation of Context.getrealpath ("/") on different servers is not the same, and for a packaged application there is no Realpath concept, and calling Getrealpath simply returns NULL. In fact, it is also very well understood that a file is packaged into a. War file, there is no directory structure (although the directory structure still exists in the package, but this is not the same as the directory structure in the file system). Therefore, the resources in the war package cannot be realpath. This makes it impossible to read through the file IO. Recommendation: (1) Replace with Servletcontext.getresourceasstream ("/web-inf/config/aa.config") methodFor example: InputStream in = This.getservletcontext (). getResourceAsStream ("/1.jpg");
(2) call This.getclass (). getClassLoader (). GetResource ("/"). GetPath (); Gets the full path to the classes directory, After getting the full path of the classes directory, the interception and assembling of the string will meet your requirements.           For example: InputStream in =new FileInputStream (This.getclass (). getClassLoader (). GetResource (".. /.. /1.jpg "). GetPath ());

About the MyEclipse servlet called This.getservletcontext (). Getrealpath () throws an exception that is null

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.