Java EE servletcontext Read the resource file

Source: Internet
Author: User

There are two ways to read the contents of a resource file ServletContext:

Method 1.

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { InputStream in = This.getservletcontext (). getResourceAsStream ("/web-inf/classes/data.properties"); Properties Pros = new properties ();p ros.load (in); String username = pros.getproperty ("username"); String Password = pros.getproperty ("password"); System.out.println ("username =" + username); SYSTEM.OUT.PRINTLN ("password =" + password);}


It is important to note that the location of the Data.properties file is in the src folder of MyEclipse, why the getResourceAsStream method passed in the argument is indeed "/web-inf/classes/data.properties "

This is because these codes have webserver to run when the project is published. The data.properties file will be placed in the directory where the Tomcat installation files are located.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbtyzmtuymtm4mw==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

So the number of references here is clear.

Method 2

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { String path = This.getservletcontext (). Getrealpath ("/web-inf/classes/data.properties"); FileInputStream in = new FileInputStream (path); Properties Pros = new properties ();p ros.load (in); String username = pros.getproperty ("username"); String Password = pros.getproperty ("password"); System.out.println ("username =" + username); SYSTEM.OUT.PRINTLN ("password =" + password);}

This first obtains the absolute path of the Data.properties file through the Getrealpath method, and then gets the file stream through FileInputStream.

Java EE servletcontext Read the resource file

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.