Reputation: 445
Can anyone suggest anything to help me. I've tried and tried and read and read but no luck.
I'm developing on Windows 7.
I'm working inside Eclipse Java EE IDE.
I'm running Java Version 8 update 77 (build 1.8.0_77-b03).
I have a Postgres database up and running fine on Cloudfoundry (version is PostgreSQL 9.4.5).
I can interact with it fine using php.
I want to interact with it through a Java servlet.
I've got my servlet all up and running fine. So now I want to add postgres functionality.
I download JDBC42 Postgresql Driver, Version 9.4-1208 from PostgreSQL JDBC Driver donwload page. I choose this one because it says of "It supports Postgresql 7.2 or newer and requires a 1.6 or newer JVM"
I add this jar file to my project's WEB_INF\lib folder. I right click on it and make sure its added to the build path. (so it now also appears under MyServletProject\Java Resources\Libraries\Web App Libraries).
I have a trivial method in my servlet: (the string jdbc_uri is the one provided to me by Cloudfoundry in response to the command cf env MyAppName in the jdbc_uri field)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
. . . . .
String szMethod = request.getParameter("method");
Connection dbcon = null;
try
{
//Class.forName("org.postgresql.Driver");
dbcon = DriverManager.getConnection(jdbc_uri,"DBusername","DBpassword");
}
catch (SQLException e)
{
szMethod = e.getMessage();
}
response.setContentType("text/html");
response.getWriter().write(szMethod);
If I run this in cloud foundry (I export from eclipse as .war file and then upload to cloud foundry, I have an HTML button which executes this servlet) I get the following message:
No suitable driver found for jdbc:postgres:// etc. etc.
You'll notice that I have commented out the line:
Class.forName("org.postgresql.Driver");
Because if I include it then in Eclipse I get a squiggly red line in the IDE and if I hover over that the context menu says:
Unhandled exception type ClassNotFoundException.
I've very stuck. It should be so simple :(
Thanks for any help. Mitch.
Upvotes: 0
Views: 1951
Reputation: 445
Solved.
The connection string provided to me by Cloudfoundry command "cf env MyApp" was wrong.
Thanks again for all the help, Mitch.
Upvotes: 1
Reputation: 361
ClassNotFoundException arises when class is not available in classpath.
So,you are creating war. Just extract war file with any zip archive and make sure is Postgresql Driver file in your war or not ? If not than build your project again.
I think you should use maven build tool for adding dependency and creating war.
Upvotes: 0
Reputation: 5442
Your code seems correct, just remove the comment and put a throw clause in your method (eclipse will do it for you if you just click on the error mark and follow the suggestions) If it cannot find the driver and will throw the exception then you should check the classpath. my advice is to use maven to manage your project dependencies.
Upvotes: 0