connect to database use properties file in java web application
22,118
Solution 1
Instead of
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
use
InputStream in = getClass().getResourceAsStream("dbConnection.properties");
Solution 2
try {
FileReader reader = new FileReader("Full Path");
Properties prop = new Properties();
prop.load(reader);
String drivers = prop.getProperty("jdbc.driverClassName");
String connectionURL = prop.getProperty("jdbc.url");
String username = prop.getProperty("jdbc.username");
String password = prop.getProperty("jdbc.password");
Class.forName(drivers);
Connection con = DriverManager.getConnection(connectionURL, username, password);
System.out.println("Connection Successful");
} catch (SQLException sqle) {
// TODO: Add catch code
sqle.printStackTrace();
} catch (FileNotFoundException fnfe) {
// TODO: Add catch code
fnfe.printStackTrace();
} catch (IOException ioe) {
// TODO: Add catch code
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe) {
// TODO: Add catch code
cnfe.printStackTrace();
}catch (Exception e) {
// TODO: Add catch code
e.printStackTrace();
}
Author by
John
Updated on July 09, 2022Comments
-
John almost 2 years
I write a code to connect to database from servlet.I want to use properties.but it does not work.i think i my code or properties file has problem.please help me to correct it.
try { Properties prop=new Properties(); FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties")); prop.load(in); in.close(); String drivers = prop.getProperty("jdbc.drivers"); String connectionURL = prop.getProperty("jdbc.url"); String username = prop.getProperty("jdbc.username"); String password = prop.getProperty("jdbc.password"); Class.forName(drivers); con=DriverManager.getConnection(connectionURL,username,password); System.out.println("Connection Successful"); ..
and this is my properties file
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver jdbc.url=jdbc:oracle:thin:@192.168.101.84:1521:orcl jdbc.username=user1 jdbc.password=123
-
John almost 11 yearsin both of instruction 'in' will be null !
-
John almost 11 yearsi create a dbConnection.properties in WEB-INF and put my info. there.so when i debug my project when it Achieve to this command it puts nothing in "in" and give me exception
-
Mark M almost 11 yearsTry removing
WEB-INF/
and see what happens. Or try to find the actual path, I can't see your system so I can't help on that part. -
nickRise about 7 years
getClass().getClassLoader().getResourceAsStream("dbConnection.properties")
should work