1 2 3 Previous Next 31 Replies Latest reply: Sep 2, 2012 3:04 AM by 905019 RSS

    How to insert data to database in jsf?

    REDO LOG
      Hi all

      How can we add data entered in inputText fields in a jsf web page to a database?

      thanks for help
        • 1. Re: How to insert data to database in jsf?
          gimbal2
          JSF does not deal with databases, it is a web framework that deals with the web. You use either the JDBC API or a higher level API like JPA to be able to do database related tasks from your managed beans.

          Before you attempt to ask for more help: the "how" question is now really answered by doing some research yourself. These are subjects that fill whole books, you are not going to be instructed in a forum (plus nobody is going to do that for free).
          • 2. Re: How to insert data to database in jsf?
            REDO LOG
            Hi
            thanks for replay

            when I said "using jsf" I really mean that I am using jsf, and primefaces 3.3.1. my goal is handle the data entered by the user in a form and sent it to database
            my problem is not with the JDBC, my problem is how to handle that data



            here is some code of what I am doing

            here is the managed bean:

            *
            package beans;

            import data.Entite;
            import data.EntitePersonnel;
            import java.io.Serializable;
            import java.sql.*;
            import java.util.ArrayList;
            import java.util.List;
            import javax.faces.bean.ManagedBean;
            import javax.faces.bean.SessionScoped;
            import javax.faces.context.FacesContext;
            import javax.servlet.http.HttpSession;


            @ManagedBean
            @SessionScoped
            public class EntiteBean implements Serializable {
            private Entite nouveauEntite;
            private String selectedChef;
            private String selectedParentEntite;

            private List<EntitePersonnel> listeEntite;

            public List<EntitePersonnel> getListeEntite() throws SQLException {
            listeEntite = new ArrayList<EntitePersonnel>();


            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);

            Connection connection = (Connection) session.getAttribute("connection");

            PreparedStatement preStmt =
            connection.prepareStatement("select designationEntite, telEntite, entiteParent, concat(nom, ' ', prenom) as Chef from entite left join (select idEntite, designationEntite as entiteParent from entite) tab1 on idEntiteParent = tab1.idEntite left join personnel on entite.matriculeChef = personnel.matricule");

            ResultSet rset = preStmt.executeQuery();

            while(rset.next()){
            Entite entite = new Entite();
            entite.setDesignationEntite(rset.getString("designationEntite"));
            entite.setTelEntite(rset.getString("telEntite"));


            String chef = rset.getString("Chef");
            String entiteParent = rset.getString("entiteParent");

            EntitePersonnel entitePersonnel = new EntitePersonnel();
            entitePersonnel.setChef(chef);
            entitePersonnel.setEntite(entite);
            entitePersonnel.setEntiteParent(entiteParent);

            listeEntite.add(entitePersonnel);
            }


            return listeEntite;
            }

            public void setListeEntite(List<EntitePersonnel> listeEntite) {
            this.listeEntite = listeEntite;
            }

            public Entite getNouveauEntite() {
            return nouveauEntite;
            }

            public void setNouveauEntite(Entite nouveauEntite) {
            this.nouveauEntite = nouveauEntite;
            }

            public String getSelectedChef() {
            return selectedChef;
            }

            public void setSelectedChef(String selectedChef) {
            this.selectedChef = selectedChef;
            }

            public String getSelectedParentEntite() {
            return selectedParentEntite;
            }

            public void setSelectedParentEntite(String selectedParentEntite) {
            this.selectedParentEntite = selectedParentEntite;
            }





            public void ajouterEntite() throws SQLException{
            nouveauEntite = new Entite();


            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
            Connection connection = (Connection) session.getAttribute("connection");

            PreparedStatement preStmt = connection.prepareCall("select matricule from personnel where concat(nom,' ',prenom) = '" + selectedChef + "'");
            ResultSet rset = preStmt.executeQuery();
            Integer matriculeChef=0;

            while(rset.next()){
            matriculeChef = rset.getInt("matricule");
            break;
            }


            preStmt = connection.prepareCall("select idEntite from entite where designationEntite = '" + selectedParentEntite + "'");
            rset = preStmt.executeQuery();

            Integer idEntite=0;
            while(rset.next()){
            idEntite = rset.getInt("idEntite");
            }


            String insertQuery = "insert into entite(designationEntite, Tel, matriculeChef, idEntiteParent) "
            + "values("
            + "'" + nouveauEntite.getDesignationEntite()+ "'"
            + ",'" + nouveauEntite.getTelEntite() + "'"
            + "," + nouveauEntite.getMatriculeChef()
            + "," + nouveauEntite.getIdEntiteParent()+ "";


            preStmt.executeUpdate(insertQuery);
            connection.commit();

            }



            public EntiteBean() {

            nouveauEntite = new Entite();
            }
            }
            *






            and here is the xhtml page:




            *
            <?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:pou="http://primefaces.org/ui"
            xmlns:f="http://java.sun.com/jsf/core">
            <h:head>
            <title>Facelet Title</title>
            </h:head>
            <h:body>
            <h:form>
            <h:panelGrid columns="2" >
            <h:outputLabel value="désignation" for="designation" />
            <pou:inputText value="#{entiteBean.nouveauEntite.designationEntite}" id="designation" />

            <h:outputLabel value="Tel" for="Tel" />
            <pou:inputText value="#{entiteBean.nouveauEntite.telEntite}" id ="Tel"/>

            <h:outputLabel value="Chef" />
            <pou:inputText value="#{entiteBean.selectedChef}" />

            <h:outputLabel value="Entite Parent" for="entite" />
            <pou:inputText value="#{entiteBean.selectedParentEntite}"/>



            <pou:commandButton value="Ajouter" action="welcomeAdmine.xhtml" immediate="true"
            actionListener="#{entiteBean.ajouterEntite()}" type="submit" ajax="false"/>







            </h:panelGrid>

            </h:form>

            </h:body>
            </html>
            *




            I user the seletedChef and selectedEntite to handle the data but nothing works

            Edited by: rachid on Aug 30, 2012 11:39 AM
            • 3. Re: How to insert data to database in jsf?
              gimbal2
              Yeah an incomplete and vague question and after 167 posts you still manage to dump wads of code without using \
               tags. Also note that "It is not working" provides absolutely zero information that is useful.                                                                                                                                                                                                                                                                                                                                                                                                                                        
              • 4. Re: How to insert data to database in jsf?
                REDO LOG
                you are not obliged to replay, and I am posting just get some help
                • 5. Re: How to insert data to database in jsf?
                  EJP
                  You're much more likely to get help if you take the trouble to make your post legible. That requires using the code formatting provisions provided.

                  It's up to you.
                  • 6. Re: How to insert data to database in jsf?
                    REDO LOG
                    sorry about that

                    now I will make my problem simple so that more people can read and understand quickly

                    I have a database(MySql) named test with only one table named person(firstName varchar(20))

                    and I want to insert values to that table from a web page :

                    so the solution is



                    a web page index.xhtml:
                    <?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">
                        <h:head>
                            <title>Facelet Title</title>
                        </h:head>
                        <h:body>
                            <h:outputLabel value="name"/>
                            <h:inputText value="#{nom.prenom}"/>
                            <h:commandButton value="click" actionListener="#{nom.addNew()}"/>
                            
                        </h:body>
                    </html>
                    and the java class to handle data :

                    package com.data;
                    
                    import java.io.Serializable;
                    import java.sql.*;
                    import javax.faces.bean.ManagedBean;
                    import javax.faces.bean.SessionScoped;
                    
                    
                    
                    
                    @ManagedBean
                    @SessionScoped
                    public class Nom implements Serializable {
                        
                        private String firstName;
                    
                        public String getFirstName() {
                            return firstName;
                        }
                    
                        public void setFirstName(String firstName) {
                            this.firstName = firstName;
                        }
                        
                        
                        public void addNew() throws ClassNotFoundException, SQLException{
                            
                            Class.forName("com.mysql.jdbc.Driver");
                            
                            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","elmaazouz");
                            
                            Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                            stmt.executeUpdate("insert into person(firstName) values ('"+ firstName +"')");
                           
                        }
                        
                    }
                    I run the application on a glassfish server and its just runs fine and properly, but when a write a name and click over the button nothing is registred in the database

                    and thats what I couldn't understand, I am missing something but I don't know what it is

                    thanks for help

                    Edited by: rachid on Aug 31, 2012 9:15 AM

                    Edited by: rachid on Aug 31, 2012 9:16 AM

                    Edited by: rachid on Aug 31, 2012 9:17 AM
                    • 7. Re: How to insert data to database in jsf?
                      EJP
                      Try closing the Statement and the Connection.
                      • 8. Re: How to insert data to database in jsf?
                        REDO LOG
                        /*
                         * To change this template, choose Tools | Templates
                         * and open the template in the editor.
                         */
                        package com.data;
                        
                        import java.io.Serializable;
                        import java.sql.*;
                        import javax.faces.bean.ManagedBean;
                        import javax.faces.bean.SessionScoped;
                        
                        /**
                         *
                         * @author ouboujlal
                         */
                        
                        
                        @ManagedBean
                        @SessionScoped
                        public class Nom implements Serializable {
                            
                            private String firstName;
                        
                            public String getFirstName() {
                                return firstName;
                            }
                        
                            public void setFirstName(String firstName) {
                                this.firstName = firstName;
                            }
                            
                            
                            public void addNew() throws ClassNotFoundException, SQLException{
                                
                                Class.forName("com.mysql.jdbc.Driver");
                                
                                Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","elmaazouz");
                                
                                Statement stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                                stmt.executeUpdate("insert into personne(nom) values ('"+ firstName +"')");
                                
                                stmt.close();
                                connection.close();
                                
                            }
                            
                        }
                        but the result still the same
                        • 9. Re: How to insert data to database in jsf?
                          EJP
                          Any evidence of an SQLException being thrown?
                          • 10. Re: How to insert data to database in jsf?
                            REDO LOG
                            no exception is thrown


                            here is the server log:

                            Launching GlassFish on Felix platform
                            INFO: Running GlassFish Version: GlassFish Server Open Source Edition 3.1.2 (build 23)
                            INFO: Grizzly Framework 1.9.46 started in: 63ms - bound to [0.0.0.0:8181]
                            INFO: Grizzly Framework 1.9.46 started in: 47ms - bound to [0.0.0.0:3700]
                            INFO: Grizzly Framework 1.9.46 started in: 16ms - bound to [0.0.0.0:7676]
                            INFO: Grizzly Framework 1.9.46 started in: 125ms - bound to [0.0.0.0:8080]
                            INFO: Grizzly Framework 1.9.46 started in: 78ms - bound to [0.0.0.0:4848]
                            INFO: The Admin Console is already installed, but not yet loaded.
                            INFO: Registered org.glassfish.ha.store.adapter.cache.ShoalBackingStoreProxy for persistence-type = replicated in BackingStoreFactoryRegistry
                            INFO: SEC1002: Security Manager is OFF.
                            INFO: SEC1010: Entering Security Startup Service
                            INFO: SEC1143: Loading policy provider com.sun.enterprise.security.provider.PolicyWrapper.
                            INFO: SEC1115: Realm [admin-realm] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
                            INFO: SEC1115: Realm [file] of classtype [com.sun.enterprise.security.auth.realm.file.FileRealm] successfully created.
                            INFO: SEC1115: Realm [certificate] of classtype [com.sun.enterprise.security.auth.realm.certificate.CertificateRealm] successfully created.
                            INFO: SEC1011: Security Service(s) Started Successfully
                            INFO: WEB0169: Created HTTP listener [http-listener-1] on host/port [0.0.0.0:8080]
                            INFO: WEB0169: Created HTTP listener [http-listener-2] on host/port [0.0.0.0:8181]
                            INFO: WEB0169: Created HTTP listener [admin-listener] on host/port [0.0.0.0:4848]
                            INFO: WEB0171: Created virtual server [server]
                            INFO: WEB0171: Created virtual server [__asadmin]
                            INFO: WEB0172: Virtual server [server] loaded default web module []
                            INFO: WELD-000900 1.1.4 (Final)
                            INFO: Hibernate Validator 4.2.0.Final
                            INFO: Initializing Mojarra 2.1.6 (SNAPSHOT 20111206) for context '/WebApp'
                            INFO: Running on PrimeFaces 3.3.1
                            INFO: Monitoring jndi:/server/WebApp/WEB-INF/faces-config.xml for modifications
                            INFO: WEB0671: Loading application [WebApp] at [/WebApp]
                            INFO: CORE10010: Loading application WebApp done in 11,672 ms
                            INFO: Initializing Mojarra 2.1.6 (SNAPSHOT 20111206) for context '/WebApplication1'
                            INFO: WEB0671: Loading application [WebApplication1] at [/WebApplication1]
                            INFO: CORE10010: Loading application WebApplication1 done in 969 ms
                            INFO: GlassFish Server Open Source Edition 3.1.2 (23) startup time : Felix (2,578ms), startup services(13,766ms), total(16,344ms)
                            INFO: WEB0169: Created HTTP listener [http-listener-1] on host/port [0.0.0.0:8080]
                            INFO: Grizzly Framework 1.9.46 started in: 15ms - bound to [0.0.0.0:8080]
                            INFO: JMX005: JMXStartupService had Started JMXConnector on JMXService URL service:jmx:rmi://ouboujlpc.home:8686/jndi/rmi://ouboujlpc.home:8686/jmxrmi
                            INFO: Created EjbThreadPoolExecutor with thread-core-pool-size 16 thread-max-pool-size 32 thread-keep-alive-seconds 60 thread-queue-capacity 2147483647 allow-core-thread-timeout false 
                            INFO: WEB0169: Created HTTP listener [http-listener-2] on host/port [0.0.0.0:8181]
                            INFO: Grizzly Framework 1.9.46 started in: 15ms - bound to [0.0.0.0:8181]
                            INFO: Initiating Jersey application, version 'Jersey: 1.11 12/09/2011 10:27 AM'
                            INFO: Initializing Mojarra 2.1.6 (SNAPSHOT 20111206) for context '/WebApplication1'
                            INFO: REST00001: Listening to REST requests at context: /management/domain
                            INFO: The Admin Console is already installed, but not yet loaded.
                            INFO: The Admin Console is starting. Please wait.
                            INFO: WEB0671: Loading application [WebApplication1] at [/WebApplication1]
                            INFO: WebApplication1 was successfully deployed in 1,984 milliseconds.
                            INFO: Initializing Mojarra 2.1.6 (SNAPSHOT 20111206) for context ''
                            INFO: WEB0671: Loading application [__admingui] at [/]
                            INFO: CORE10010: Loading application __admingui done in 5,219 ms
                            INFO: The Admin Console application is loaded.
                            • 11. Re: How to insert data to database in jsf?
                              905019
                              You know the method is being executed?
                              You sure you are in a transaction?
                              • 12. Re: How to insert data to database in jsf?
                                gimbal2
                                Its MySQL, connection is auto-commit by default.
                                You know the method is being executed
                                That is a very interesting question however. Its just reasonable to assume that when you expect stuff to happen but it is not happening, you're not actually making it happen.
                                • 13. Re: How to insert data to database in jsf?
                                  REDO LOG
                                  Hi

                                  I really don't know if the method is being executed, but I will make a modification and ask the server to redirect me to another page when I click the button so that I make sure of the execution of the method

                                  I just want to remind that I am using netbeans 7.1.2, mysql 5.25 and glassfish server 3.1.2
                                  • 14. Re: How to insert data to database in jsf?
                                    REDO LOG
                                    you question was legitimate,

                                    here is the changes

                                    /*
                                     * To change this template, choose Tools | Templates
                                     * and open the template in the editor.
                                     */
                                    package com.data;
                                    
                                    import com.mysql.jdbc.Connection;
                                    import com.mysql.jdbc.Statement;
                                    import java.io.Serializable;
                                    import java.sql.DriverManager;
                                    import java.sql.ResultSet;
                                    import java.sql.SQLException;
                                    import javax.faces.bean.ManagedBean;
                                    import javax.faces.bean.SessionScoped;
                                    
                                    /**
                                     *
                                     * @author ouboujlal
                                     */
                                    
                                    
                                    @ManagedBean
                                    @SessionScoped
                                    public class Nom implements Serializable {
                                        
                                        private String firstName;
                                    
                                        public String getFirstName() {
                                            return firstName;
                                        }
                                    
                                        public void setFirstName(String firstName) {
                                            this.firstName = firstName;
                                        }
                                        
                                        
                                        public String addNew() throws ClassNotFoundException, SQLException{
                                            
                                            Class.forName("com.mysql.jdbc.Driver");
                                            Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","elmaazouz");
                                            
                                            Statement stmt = (Statement) connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
                                            stmt.executeUpdate("insert into personne values ('"+ firstName +"')");
                                            
                                            connection.commit();
                                            stmt.close();
                                            connection.close();
                                            
                                            
                                            return "welcome";
                                            
                                        }
                                        
                                    }
                                    here is the index page:


                                    <?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">
                                        <h:head>
                                            <title>Facelet Title</title>
                                        </h:head>
                                        <h:body>
                                            <h:outputLabel value="name"/>
                                            <h:inputText value="#{nom.firstName}"/>
                                            <h:commandButton value="click" action="#{nom.addNew()}"/>
                                            
                                        </h:body>
                                    </html>
                                    here is the welcome page


                                    <?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">
                                        <h:head>
                                            <title>Facelet Title</title>
                                        </h:head>
                                        <h:body>
                                            Hello #{nom.firstName}
                                        </h:body>
                                    </html>
                                    logically, when the button is clicked, the addNew() method execute the code and then return the string "welcome" and then the server redirect me the welcome page, nut unfortunately it didn't . I guess that the method isn't being executed
                                    1 2 3 Previous Next