Problem integrating .xhtml code with .java

UI Components for JSF
Post Reply
LucasVerissimo
Posts: 3
Joined: 18 Jun 2023, 04:55
Location: Montes Claros - MG

18 Jun 2023, 05:44

Good night guys!

I'm starting to use PrimeFaces and its components, as well as JSF and Java. I'm facing problems sending the data to the database.

When I use this first .xhtml code:

Code: Select all

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">

<h:head>

</h:head>

<h:body>
      <h:form>
           <p:messages id="messages" />
           <p:panelGrid columns="2">
                 <p:outputLabel for="id" value="ID:" />
                 <p:spinner id="id" value="#{UserMB.user.id}" />


                 <p:outputLabel for="name" value="Name:" />
                 <p:inputText id="name" value="#{UserMB.user.name}" />


                 <p:outputLabel for="password" value="Password:" />
                 <p:inputText id="password" value="#{UserMB.user.password}" />


                 <p:outputLabel for="description" value="Description:" />
                 <p:inputTextarea id="description"
                      value="#{UserMB.user.description}" />

                 <p:commandButton value="Register" icon="ui-icon-star"
                  action="#{UserMB.registerUser}" update="messages">
                 </p:commandButton>

           </p:panelGrid>
      </h:form>
</h:body>
</html>
Combined with this .java file:

Code: Select all

package control;

import java.sql.SQLException;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import model.Connect;
import model.User;

@ManagedBean(name = "UserMB")
public class UserMB {

      private User user = new User();

      public String registerUser() throws SQLException {
           Connect con = new Connect();

           if (con.insertUser(user)) {
                FacesContext.getCurrentInstance().addMessage(null,
                          new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Successfully registered user!"));
           } else {
                FacesContext.getCurrentInstance().addMessage(null,
                          new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "User registration error!"));
           }
           con.closeConnection();

           return "";
      }

      public List<User> getUsers() throws SQLException {
           Connect con = new Connect();
           List<User> listUsers = con.listUsers();

           return listUsers;
      }

      public User getUser() {
           return user;
      }

      public void setUser(User user) {
           this.user = user;
      }
}
The application manages to write the data normally, but when I use this .xhtml file, which uses other components:

Code: Select all

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui">

<h:head>
     <!-- CSS styles -->
     <style>
    
         /* Style for text and response */
         .bold-font {
             font-weight: bold;
             font-family: Calibri;
             color: #042AAF; /* Text color */
         }
        
         /* Style for the body of the page */
         body {
             background: linear-gradient(to bottom, #0180FF, #FFFFFF);
             margin: 0;
             padding: 0;
             display: flex;
             flex-direction: column;
             align-items: center;
             justify-content: center;
             height: 100vh; /* Set the page height to 100% of the viewport height */
         }
        
         /* Style for the back button */
         .back-button {
             position: absolute;
             top: 10px;
             left: 10px;
             background-color: #FFFFFF;
             color: #042AAF;
             border: none;
             border-radius: 5px;
             padding: 5px 15px;
             cursor: pointer;
             font-weight: bold;
             font-family: Calibri;
             display: flex;
             align-items: center;
             transition: transform 0.3s, box-shadow 0.3s;
         }
        
         .back-button:hover {
             transform: translateY(-3px);
             box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
         }
        
         .back-button:hover::before {
             content: "Back";
             position: absolute;
             top: 20px;
             left: 120%;
             transform: translateX(-50%);
             background-color: #042AAF;
             color: #FFFFFF;
             font-size: 12px;
             padding: 3px 6px;
             border-radius: 5px;
             opacity: 1;
             pointer-events: none;
             transition: opacity 0.3s;
         }
        
         .back-button::after {
             content: "";
             display: inline-block;
             margin-left: 5px;
             border: solid #042AAF;
             border-width: 0 2px 2px 0;
             padding: 3px;
             transform: rotate(135deg);
         }
        
         /* Style for the button container */
         .button-container {
             display: flex;
             flex-direction: column;
             align-items: center;
             margin-bottom: 50px;
             margin-top: 25px;
         }
        
         /* Style for the buttons */
         .button {
             background-color: #FFFFFF; /* Button background color */
             fontsize: 20px; /* Button font size */
             color: #042AAF; /* Button text color */
             border: none; /* Remove border from buttons */
             border-radius: 10px; /* Round the corners of the buttons */
             padding: 10px 30px; /* Button spacing */
             margin-bottom: 20px; /* Bottom spacing between buttons */
             cursor: pointer; /* Mouse cursor when hovering over buttons */
             font-weight: bold;
             font-family: Calibri; /* Button font */
             width: 200px; /* Fixed width of buttons */
         }
        
         .button.elevate:hover {
             transform: translateY(-5px);
             box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
         }
        
         /* Style to round panel edges */
         .rounded-panel {
             border-radius: 10px; /* Round the corners of the panel */
             overflow: hidden; /* Hide any content that extends beyond the rounded edges */
         }
        
         /* Style for terms of use text */
         .terms-text {
             font-size: 12px;
             font-family: Calibri;
             color: #042AAF;
             margin-top: 20px;
             text-align: justify;
         }
        
         /* Style for the Privacy Policy link */
         .terms-link {
             color: #042AAF;
             text-decoration: underline;
             cursor: pointer;
         }
        
         /* Style for the labels and captions panel */
         .label-legend-panel {
             background-color: #FFFFFF;
             padding: 10px;
             border-radius: 10px;
             margin-right: -5px;
             margin-left: -6px;
             margin-bottom: 0px;
             display: flex;
             align-items: center;
         }
        
         /* Style for subtitles */
         .legend {
             margin-right: 10px;
             text-align: right;
             flex: 0 0 95px;
             font-weight: normal;
         }
        
         /* Style for the labels */
         .label {
             font-weight: bold;
             margin-right: 50px;
             margin-left: 0px;
         }
     </style>
</h:head>

<h:body>

     <!-- Back button -->
     <a class="back-button" href="home.jsf"></a>
    
     <!-- Container and input fields -->
     <div class="label-legend-panel">
     <div class="rounded-panel">
    
         <!-- Panel for the user field -->
         <div class="label-legend-panel">
             <div class="legend" style="font-family: Calibri; color: #042AAF; font-weight: bold; font-size: 18px;">Username:</div>
             <div class="label" ><p:inputText id="name" value="#{UserMB.user.name}" style="width: 300px;" /></div>
         </div>
        
         <!-- Panel for password field -->
         <div class="label-legend-panel">
             <div class="legend" style="font-family: Calibri; color: #042AAF; font-weight: bold; font-size: 18px;">Password:</div>
             <div class="label" ><p:password id="password" value="#{UserMB.user.password}" style="width: 300px;" /></div>
         </div>
        
         <!-- Panel for description and gender field -->
         <div class="label-legend-panel">
             <div class="legend" style="font-family: Calibri; color: #042AAF; font-weight: bold; font-size: 18px;">Description:</div>
             <div class="label">
                 <p:selectOneMenu id="description" value="#{UserMB.user.description}" styleClass="bold-font">
                    <f:selectItem itemLabel="Select" itemValue="" />
                    <f:selectItem itemLabel="Deliver" itemValue="Deliver" />
                    <f:selectItem itemLabel="Customer" itemValue="Customer" />
                    <f:selectItem itemLabel="Contributor" itemValue="Contributor" />
                 </p:selectOneMenu>
             </div>
            
             <div class="legend" style="font-family: Calibri; color: #042AAF; font-weight: bold; font-size: 18px; flex:0 1 100px;">Gender:</div>
             <div class="label">
                 <p:selectOneMenu id="gender" value="#{UserMB.user.gender}" styleClass="bold-font" style="width: 60px;">
                    <f:selectItem itemLabel="---" itemValue="" />
                    <f:selectItem itemLabel="M" itemValue="Male" />
                    <f:selectItem itemLabel="F" itemValue="Female" />
                 </p:selectOneMenu>
             </div>
         </div>
            
         <!-- Growl component for displaying messages -->
         <p:growl id="growl" sticky="false" life="3000" />
        
     </div>
     </div>
    
     <!-- Button container -->
     <div class="button-container">
        <h:commandButton class="button elevate" value="Register" action="#{UserMB.registerUser}" onclick="clearLabels()" />
        <!-- JavaScript function to clear the labels -->
        <script>
             function clearLabels() {
                 document.getElementById("name").value = "";
                 document.getElementById("password").value = "";
             }
        </script>
     </div>
    
     <!-- Text of Terms of Use and Privacy Policy -->
     <p class="terms-text">
         By continuing, you agree to the Terms of Use. Read our
         <span class="terms-link" onclick="window.open('privacy_policy.html')">Privacy Policy</span>.
     </p>
</h:body>
</html>
The data is not recorded, even pressing the "Register" button, the code does not even interact with the "UsuarioMB" class, it does not return any type of message. Why does it happen? How can I resolve this?

In summary: the first code .xhtml interacts normally with the code .java and the data is sent to the database, while in the second this does not happen.

Remembering that I'm using the Eclipse IDE to make a Maven project. It has the following dependencies:
https://prnt.sc/l7jtaI_MbBjs

Below are the codes of the other classes that make up the application:

Code: Select all

package model;

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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Connect {
      Connection con = null;

      public Connect() throws SQLException {
           try {
                 Class.forName("com.mysql.jdbc.Driver");
                 System.out.println("Install driver");
           } catch (ClassNotFoundException e) {
                 e.printStackTrace();
           }

           String url = "jdbc:mysql://localhost:3306/user";
           String user = "root";
           String password = "123";
           con = DriverManager.getConnection(url, user, password);
      }

      public void closeConnection() throws SQLException {
           con.close();
      }

      public boolean insertUser(User user) {
           try {
                 PreparedStatement preparedStatement = con.prepareStatement("insert into user(name, password, description, gender, registration_date) values(?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
                 preparedStatement.setString(1, user.getName());
                 preparedStatement.setString(2, user.getPassword());
                 preparedStatement.setString(3, user.getDescription());
                 preparedStatement.setString(4, user.getGender());
                 preparedStatement.setDate(5, new java.sql.Date(new Date().getTime()));

                 preparedStatement.executeUpdate();

                 ResultSet rs = preparedStatement.getGeneratedKeys();
                 if (rs.next()) {
                     int id = rs.getInt(1);
                     user.setId(id);
                 }

                 return true;
           } catch (SQLException ex) {
                 Logger lgr = Logger.getLogger(Connect.class.getName());
                 lgr.log(Level.SEVERE, ex.getMessage(), ex);
                 return false;
           }
      }

      public List<User> listUsers() {
           ArrayList<User> list = new ArrayList<User>();

           Statement st = null;
           ResultSet rs = null;

           try {
                 st = con.createStatement();
                 String sql = "select * from user";
                 rs = st.executeQuery(sql);

                 while (rs.next()) {
                      User user = new User();
                      user.setId(rs.getInt(1));
                      user.setName(rs.getString(2));
                      user.setPassword(rs.getString(3));
                      user.setDescription(rs.getString(4));
                      user.setGender(rs.getString(5));
                      user.setRegistrationDate(rs.getDate(6));
                      list.add(user);
                 }

           } catch (SQLException ex) {
                 Logger lgr = Logger.getLogger(Connect.class.getName());
                 lgr.log(Level.SEVERE, ex.getMessage(), ex);
           } finally {
                 try {
                      if (rs != null) {
                           rs.close();
                      }
                      if (st != null) {
                           st.close();
                      }
                      if (con != null) {
                           con.close();
                      }
                 } catch (SQLException ex) {
                      Logger lgr = Logger.getLogger(Connect.class.getName());
                      lgr.log(Level.WARNING, ex.getMessage(), ex);
                 }
           }
           return list;
      }
}

Code: Select all

package model;

import java.util.Date;

public class User {

      private int id;
      private String name;
      private String password;
      private String gender;
      private Date registrationDate;
      private String description;

      public int getId() {
           return id;
      }
      public void setId(int id) {
           this.id = id;
      }
     
      public String getName() {
           return name;
      }
      public void setName(String name) {
           this.name = name;
      }
     
      public String getPassword() {
           return password;
      }
      public void setPassword(String password) {
           this.password = password;
      }
     
      public Date getRegistrationDate() {
           return dataCadastro;
      }
      public void setRegistrationDate(Date registrationDate) {
           this.registrationDate = registrationDate;
      }
     
      public String getGender() {
          return gender;
     }
     public void setGender(String gender) {
          this.gender = gender;
     }
     
      public String getDescription() {
           return description;
      }
      public void setDescription(String description) {
           this.description = description;
      }
}
I beg your pardon if there are any English mistakes, my native language is Portuguese-br.

Att,
Lucas Verissimo.
PrimeFaces 11.0.0

NOTiFY
Posts: 393
Joined: 25 May 2016, 22:57

19 Jun 2023, 13:11

For starters change:

Code: Select all

@ManagedBean(name = "UserMB")
to:

Code: Select all

@ManagedBean(name = "userMB")
For Database no Entity or 'persistence.xml":

Code: Select all

@Entity(...)
You should also be using Jakarta Faces 4.0:

Code: Select all

<html
        xmlns:f="jakarta.faces.core"
        xmlns:h="jakarta.faces.html"
        xmlns:p="http://primefaces.org/ui"
>
So need to use PrimeFaces: https://jakarta.ee/specifications/faces/

https://repo1.maven.org/maven2/org/prim ... 3.0.0-RC1/

Code: Select all

org/primefaces/primefaces/13.0.0-RC1

primefaces-13.0.0-RC1-jakarta.jar 
Also are you using a Jakarta EE Application Server like WildFly, GlassFish, Quarkus or Apache TomEE (https://jakarta.ee/compatibility/) ?
Last edited by NOTiFY on 21 Jun 2023, 10:12, edited 8 times in total.
PF 13.0.0--Jakarta. Jakarta Faces 4.0.1/Kotlin Multiplatform 1.9.10
Mojarra 4.0.2, OmniFaces 4.2
WildFly 29.0.1.Final 'preview' Jakarta EE 10.0.0
JDK 20.0.2, Kotlin 1.9.10, Gradle 8.3 Groovy DSL, MongoDB 7.0.0
IntelliJ IDEA 2023.2.1, macOS Ventura 13.5.1

LucasVerissimo
Posts: 3
Joined: 18 Jun 2023, 04:55
Location: Montes Claros - MG

20 Jun 2023, 02:25

NOTiFY wrote:
19 Jun 2023, 13:11

Code: Select all

@ManagedBean(name = "userMB")
etc.
Goodnight friend!

I'm really starting, explain it like you're talking to a rock, I couldn't understand your "etc".
PrimeFaces 11.0.0

LucasVerissimo
Posts: 3
Joined: 18 Jun 2023, 04:55
Location: Montes Claros - MG

22 Jun 2023, 20:32

NOTiFY wrote:
19 Jun 2023, 13:11
For starters change:

Code: Select all

@ManagedBean(name = "UserMB")
to:

Code: Select all

@ManagedBean(name = "userMB")
For Database no Entity or 'persistence.xml":

Code: Select all

@Entity(...)
You should also be using Jakarta Faces 4.0:

Code: Select all

<html
        xmlns:f="jakarta.faces.core"
        xmlns:h="jakarta.faces.html"
        xmlns:p="http://primefaces.org/ui"
>
So need to use PrimeFaces: https://jakarta.ee/specifications/faces/

https://repo1.maven.org/maven2/org/prim ... 3.0.0-RC1/

Code: Select all

org/primefaces/primefaces/13.0.0-RC1

primefaces-13.0.0-RC1-jakarta.jar 
Also are you using a Jakarta EE Application Server like WildFly, GlassFish, Quarkus or Apache TomEE (https://jakarta.ee/compatibility/) ?
Thanks a lot for your contribution.

I'm using Apache Tomcat, my problem is above all the calls made by .xhtml in relation to "UserMB.java", I press the "Register" button and neither the "Error!" appears on the screen, which in my view as a layman, it's like the backend doesn't exist.
PrimeFaces 11.0.0

NOTiFY
Posts: 393
Joined: 25 May 2016, 22:57

22 Jun 2023, 21:22

all the calls made by .xhtml in relation to "UserMB.java",
IMO: I would just put a 'System' or 'Log' on your 'Controller':

Code: Select all

@ManagedBean(name = "userMB") 
Which will show that/if 'PrimeFaces' Java Faces is called from your XHTML.
PF 13.0.0--Jakarta. Jakarta Faces 4.0.1/Kotlin Multiplatform 1.9.10
Mojarra 4.0.2, OmniFaces 4.2
WildFly 29.0.1.Final 'preview' Jakarta EE 10.0.0
JDK 20.0.2, Kotlin 1.9.10, Gradle 8.3 Groovy DSL, MongoDB 7.0.0
IntelliJ IDEA 2023.2.1, macOS Ventura 13.5.1

Post Reply

Return to “PrimeFaces”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 24 guests