In the Web, ordinary classes do not pass the This.getservletcontext (). getResourceAsStream () to get the Web resources, which need to be loaded through the ClassLoader, there are two ways to do this, and the two ways are different. Download Let's have a look at it.
Method 1.
public class Userdao {public void Connect () throws IOException {method1 ();} private void Method1 () throws IOException {InputStream in = UserDao.class.getClassLoader (). getResourceAsStream (" Db.properties "); Properties props = new properties ();p rops.load (in); String url = props.getproperty ("url"); String username = props.getproperty ("username"); String Password = props.getproperty ("password"); System.out.println ("url:" + URL); System.out.println ("Username:" + username); System.out.println ("Password:" + password);}}
When a resource file is obtained in this way, the resource file is only loaded once by the ClassLoader when the server is started, and will not be loaded again, that is, when I modify the Web resource file data, the last output data will not change, or the same as the previous data.
Test:
My Web resource file here is the Db.properties file.
When I change the value of the URL to card,card111,card222 every time, the result of the console output is card.
It is important to note that The modified Db.properties file must be a Web project after the release, go to the Tomcat directory to modify, if you modify the Db.properties file in MyEclipse is meaningless, because after the project is published, all the files under SRC will be copied to Tomcat Web application directory ,
Each time you finish modifying the Db.properties file, save and then refresh the webpage, myeclpse do not do any action.
Console output Results:
Method 2:
public class Userdao {public void Connect () throws IOException {method2 ();} private void Method2 () throws IOException {String path = UserDao.class.getClassLoader (). GetResource ("Db.properties"). GetPath (); FileInputStream in = new FileInputStream (path); Properties props = new properties ();p rops.load (in); String url = props.getproperty ("url"); String username = props.getproperty ("username"); String Password = props.getproperty ("password"); System.out.println ("url:" + URL); System.out.println ("Username:" + username); System.out.println ("Password:" + password);}}
First, change the db.properties file URL value in the Tomcat directory back to card. Then restart the server.
Change the value of the URL again to card,card111,card222
The results are as follows:
Here I have a question is, I use Tomcat6 here, if you change the TOMCAT7, each time you modify the resources, both methods will be loaded again, that is, the result of the output is the value you modified.
What is it for? There is a great God in the wood to do a little deeper solution