0

所以简而言之,这是我的问题:我正在尝试创建一个 JSF 页面和一个 Java 类来连接到数据库(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>

所以,我以为我有它,直到我运行整个事情只是遇到了一个小问题:页面出现了,我仍然没有得到任何价值!

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

编辑 :

堆栈跟踪结果包含以下内容:

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

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

4

2 回答 2

0

这是主要问题: SQLException: 找不到合适的驱动程序。看起来你忘记加载驱动程序了。由于您处于学习阶段,因此您可以使用Class.forName(<driver class name>);. 基于有关加载驱动程序的 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 等)管理的数据库连接池。

于 2013-04-29T17:09:31.063 回答
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-捕获异常并通过堆栈跟踪代码处理它们以隔离问题,2-不要像我犯的那样犯愚蠢的错误:例如在getConnection方法中,url字符串以“jdbc:postgresql”而不是“jdbc:postgres”开头。从可行的来源复制粘贴是更好的编码实践。

我认为今天应该是这样,祝大家好运,学习愉快:)!

于 2013-04-30T08:21:33.233 回答