PDA

View Full Version : JSF + JDBC-MySQL


Caterpillar86
29-09-2011, 22:19
Sto sviluppando pagine xhtml con JavaServerFaces con l'aiuto di questo libro:
http://horstmann.com/corejsf/
In questo istante sto testando la visualizzazione di tabelle di database su pagina web.

Tuttavia ho dei problemi. Ora vi illustro da zero la procedura che ho seguito.
Da Eclipse:
Nuovo->Dynamic web project
Proprietà-> facet progetto->abilito JSF 2.0
vado su WebContent->WEB-INF->faces-config.xml (apro da interfaccia grafica)
Scheda ManagedBean->aggiungi->creo la classe Database con RequestScope

Dentro Database.java c'è:

package classes;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;
import javax.annotation.Resource;


@ManagedBean
@RequestScoped
public class Database
{
private static Statement statement = null;
private static Connection connection = null;
private ResultSet result = null;

public static void main(String[] args)
{
try
{
connection = getConnection();
statement = connection.createStatement();
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM tabella");
while(result.next())
{
System.out.println(result.getNString(1));
}
System.out.println("\n");
ResultSet result2 = stmt.executeQuery("SELECT * FROM tabella");
while(result2.next())
{
System.out.println(result2.getString(1));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}

}

/*public ResultSet getAll()
{
try
{
connection = getConnection();
statement = connection.createStatement();
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM tabella");
CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl();
crs.populate(result);

}
catch (SQLException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
return crs;
connection.close();
}
}*/


public ResultSet getAll() throws SQLException, IOException
{
//try
//{
connection = getConnection();
statement = connection.createStatement();
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM tabella");
CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl();
crs.populate(result);
return crs;
//}
/*finally
{
connection.close();
}*/

}


/**
Gets a connection from the properties specified
in the file database.properties
@return the database connection
*/
public static Connection getConnection()
throws SQLException, IOException
{
Properties props = new Properties();
FileInputStream in = new FileInputStream("/home/caterpillar/workspace/cancTestDatabaseExNovo/database.properties");
props.load(in);
in.close();

String drivers = props.getProperty("jdbc.drivers");
if (drivers != null)
System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");

return DriverManager.getConnection(url, username, password);
}
private PreparedStatement insertStatement;
private PreparedStatement rispostaStatement;
private static final String insertString = "INSERT INTO (?) VALUES (?, ?)";
private static final String insertStringV2 = "INSERT INTO (?) VALUES (?)";
private static final String risposta = "SELECT * FROM tabella";
}


Dentro database.properties c'è:

jdbc.drivers=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=nascosto


Dentro index.xhtml c'è:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>

<title>pageTitle</title>
</h:head>
<h:body>
<h:form>
<h:dataTable value="#{database.all}" var="lista">

<h:column>
#{lista.Parola}
</h:column>

</h:dataTable>
</h:form>
</h:body>
</html>

Siccome dentro la cartella di /lib di Tomcat c'è il mysql-connector, sapreste spiegarmi perchè esce fuori questo messaggio di errore quando faccio partire index.xhtml?
An Error Occurred:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8

Caused by:
java.sql.SQLException - No suitable driver found for jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
È più di un giorno intero che sto dietro a questo errore ed altri che sono usciti fuori nelle varie prove........


Lo StackTrace dice:
javax.faces.FacesException: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.wrap(ExceptionHandlerImpl.java:241)
at org.apache.myfaces.shared_impl.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:156)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:258)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:185)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:151)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
at java.sql.DriverManager.getConnection(DriverManager.java:640)
at java.sql.DriverManager.getConnection(DriverManager.java:200)
at classes.Database.getConnection(Database.java:126)
at classes.Database.getAll(Database.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:142)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at org.apache.myfaces.view.facelets.el.TagValueExpression.getValue(TagValueExpression.java:85)
at javax.faces.component._DeltaStateHelper.eval(_DeltaStateHelper.java:243)
at javax.faces.component.UIData.getValue(UIData.java:1153)
at javax.faces.component.UIData.createDataModel(UIData.java:1101)
at javax.faces.component.UIData.getDataModel(UIData.java:1078)
at javax.faces.component.UIData.getRowCount(UIData.java:457)
at org.apache.myfaces.shared_impl.renderkit.html.HtmlTableRendererBase.encodeInnerHtml(HtmlTableRendererBase.java:289)
at org.apache.myfaces.shared_impl.renderkit.html.HtmlTableRendererBase.encodeChildren(HtmlTableRendererBase.java:173)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:488)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:609)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:614)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:614)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:614)
at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1159)
at org.apache.myfaces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:263)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:85)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:239)
... 17 more

Il file web.xml l'ho lasciato così come l'ha creato Eclipse, tanto ci dovrebbe pensare lui a quello

Caterpillar86
03-10-2011, 15:14
Ho risolto mettendo la riga
System.out.println(insertStatement.toString());
nel public static Connection getConnection()