将jsf连接到postgres,出了什么问题?

时间:2013-04-29 15:45:45

标签: jsf managed-bean

所以这就是我的问题:我正在尝试创建一个JSF页面和一个Java类来连接到DB(postgres)。目标是从数据库中提取结果,然后在JSF上显示它,非常简单吧?

我的代码如下:

JSF是:

<?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:h="http://java.sun.com/jsf/html"
      xmlns:c="http://java.sun.com/jsp/jstl/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        Hello from Facelets
        <p>${calendar.form}</p>
    </h:body>
</html>

至于Java:

import java.sql.*;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;

@ManagedBean(name="calendar")
@ViewScoped 
@RequestScoped

public class Calendar {
    private String form = null;

    public String getForm() {
        return form;
    }

    public void setForm(String form) {
        this.form = form;
    }

    public Calendar(){
        /* Connexion à la base de données */
        String url = "jdbc:postgres://localhost:5432/postgres";
        String utilisateur = "postgres";
        String motDePasse = "123456789";
        Connection connexion = null;
        try {
            connexion = DriverManager.getConnection( url, utilisateur, motDePasse );

            /* Ici, nous placerons nos requêtes vers la BDD */
            /* ... */
            /* Création de l'objet gérant les requêtes */
            Statement statement = connexion.createStatement();
            /* Exécution d'une requête de lecture */
            ResultSet resultat = statement.executeQuery( "SELECT *  FROM detaillant WHERE date= \"2013-04-25\" ;" );
            resultat.next();
            setForm(resultat.getString( "form" )); 
                /* Traiter ici les valeurs récupérées. */
        } catch ( SQLException e ) {
            /* Gérer les éventuelles erreurs ici */
        } finally {
            if ( connexion != null )
                try {
                    /* Fermeture de la connexion */
                    connexion.close();
                } catch ( SQLException ignore ) {
                    /* Si une erreur survient lors de la fermeture, il suffit de l'ignorer. */
                }
        }
      }//END of constructor

}

在我的web.xml中,我确保从JSF页面(在我的例子中命名为index)启动我的应用程序,如下所示:

<welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>

所以,我认为我已经拥有它,直到我运行整个事情只是为了碰到一个小问题:页面出现,但我没有得到任何价值!

那么,任何关于我可能会改变它以使其工作的想法?提前谢谢!

编辑:

stacktrace包含以下内容:

com.sun.faces.mgbean.ManagedBeanCreationException: Impossible dinstancier la classe Calendar.
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:71)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:147)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
    at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:224)
    at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:85)
    at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
    at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    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:169)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    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.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:304)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.FacesException: java.sql.SQLException: No suitable driver found for jdbc:postgres://localhost:5432/postgres
    at Calendar.<init>(Calendar.java:48)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:374)
    at java.lang.Class.newInstance(Class.java:327)
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
    ... 41 more
Caused by: java.sql.SQLException: No suitable driver found for jdbc:postgres://localhost:5432/postgres
    at java.sql.DriverManager.getConnection(DriverManager.java:604)
    at java.sql.DriverManager.getConnection(DriverManager.java:221)
    at Calendar.<init>(Calendar.java:27)
    ... 48 more

对于一个初学者来说,这是一个热门的盘子哈哈...

2 个答案:

答案 0 :(得分:0)

这是主要问题:SQLException:找不到合适的驱动程序。看起来你忘了加载驱动程序。由于您处于学习阶段,因此可以使用Class.forName(<driver class name>);执行此操作。基于有关loading the driver的PostreSQL文档:

 String url = "jdbc:postgres://localhost:5432/postgres";
 String utilisateur = "postgres";
 String motDePasse = "123456789";
 Connection connexion = null;
 try {
      Class.forName("org.postgresql.Driver");
      connexion = DriverManager.getConnection( url, utilisateur, motDePasse );
      //rest of code...
 } catch (SQLException e) {
      //this is a basic way to handle errors...
      e.printStackTrace();
 } catch (ClassNotFoundException e) {
      e.printStackTrace();
 } catch (Exception e) {
      e.printStackTrace();
 }
 //...

在真实世界的应用程序中,您将使用由应用程序服务器(Tomcat,Jboss等)管理的数据库连接池。

答案 1 :(得分:0)

我想我会发布反馈,因为它有效,所以它可能对将来的其他人有所帮助:

 Connection connexion = null;
        try {
            try {
                Class.forName("org.postgresql.Driver");
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Calendar.class.getName()).log(Level.SEVERE, null, ex);
            }
            connexion = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "123456789" );

            /* Ici, nous placerons nos requêtes vers la BDD */
            /* ... */
            /* Création de l'objet gérant les requêtes */
            Statement statement = connexion.createStatement();
            /* Exécution d'une requête de lecture */
            ResultSet resultat = statement.executeQuery( "SELECT *  FROM detaillant WHERE retailer_id = 101001 ;" );
            resultat.next();
            setForm(resultat.getString( "form" )); 
            resultat.close();
            statement.close();
            connexion.close();
                /* Traiter ici les valeurs récupérées. */
        } catch ( SQLException e ) {
            /* Gérer les éventuelles erreurs ici */
            throw new FacesException(e) ;
        } finally {
            if ( connexion != null )
                try {
                    /* Fermeture de la connexion */
                    connexion.close();
                } catch ( SQLException ignore ) {
                    /* Si une erreur survient lors de la fermeture, il suffit de l'ignorer. */
                }
        }

几点不要忘记:

1-捕获异常并通过stacktrace代码处理它们以隔离问题, 2-不要像我所做的那样犯下愚蠢的错误:例如,在getConnection方法中,url字符串以“jdbc:postgresql”而不是“jdbc:postgres”开头。从可行的来源复制粘贴是更好的编码实践。

我认为应该是白天,祝所有人好运,并且学习得很好:)!