I'm working on my first Java EE project with Eclipse Juno, Java 7, Tomcat 7 and MySQL 5.5, with the goal of creating a servlet, a JSP view and some models. But I have a big problem of connection to the database inside the servlet. First I was connecting directly from the servlet, and then calling a DBConnection object that I created, anyway it doesn't change the problem because I'm quite sure I did it correctly as written below but still a connection problem :
public class servphilo extends HttpServlet {
ResultSet listeEtat;
DBConnection conn = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
conn=new DBConnection();
System.out.println("création objet connexion OK");
} catch(Exception e) {
e.printStackTrace();
}
try {
conn.getDBConnection();
} catch (Exception e) {
e.printStackTrace();
}
this.getServletContext().getRequestDispatcher( "/WEB-INF/view.jsp" ).forward( request, response );
}
}
public class DBConnection {
Connection conn = null;
public DBConnection () {
//System.out.println("objet DBconnection OK");
}
public Connection getDBConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String sUserName="aaa";
String sPwd="bbb";
System.setProperty("java.net.preferIPv4Stack" , "true");
conn = DriverManager.getConnection("jdbc:mysql://localhost/base",sUserName,sPwd);
System.out.println("objet DBconnection OK");
return conn;
}
}
From the browser the JSP view is sent correctly but the console of Eclipse write this message :
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
The line System.setProperty("java.net.preferIPv4Stack" , "true"); that you can see below was the former idea to the connection in IPv4 from a classical Java class and it worked well, but now with servletit doesn't.
Is it the same problem with Tomcat that we must force on IPv4 ? What can I do precisely (files, line, etc.) ? Thanks for helping me.