< Using JPA and JSF ver 2 (MySQL) | Main | Steps on Moving NetBeans Project >

 


 

 

 

Java Web GUI Application:

Modifying Database Table with the JPA (MySQL) Version 2 Part 2

 

 

 

This is the second part version 2 tutorial in a two-part series. In this tutorial we will use the same Java Persistence API (JPA) and Visual Web (JSF) Table component to add, update, and delete database table rows. The table printing using CSS also will be included.

 

Contents:

  1. Prerequisites

  2. Introduction

  3. Modify the Java Database Access Class

  4. Modify the Web Page Design

  5. Use Grid Panel Components to Control Page Display

  6. Use the Navigator Window to Position Components

  7. Add Remaining Components to Page

  8. Customize Table Display Using Table Layout

  9. Add Logic for Button Components

  10. Write Java Code for the Radio Buttons

  11. Add JavaScript Code to the JavaServer Page File

  12. Bind the Radio Button to the Table Component

  13. Write Code for Button Handler Methods

  14. Create Boolean Variables

  15. Write Button Action Handler Methods

  16. Write Code to Create Entity Bean and Add to Database

  17. Write Code to Update Database Record

  18. Modify prerender Method to Control Page Display

  19. Run the Application

  20. Testing the Application

  21. Printing the Table Data Using CSS

  22. Testing the Table Printing Feature

Prerequisites

 

This is the second part version 2 in a two-part series. You should have completed the first part and have created the two projects described in that tutorial, along with the different classes and web page. The first tutorial provides all the information necessary to set up these two projects.

 

 

Introduction

 

The first tutorial provided background on the Java Persistence API. It walked you through the steps to use the Java Persistence API to access a database table and retrieve its data, and then display that data using a Visual Web Table component. Recall that you created two projects, a MyTestModelApp standard JSE project and a TestWebApp Visual Web project. You also created a page in MyTestWebApp to display database table data, and two classes containing Java Persistence API methods, Users and UserController, in MyTestModelApp. You also included code in TestWebApp to invoke methods on the two classes in MyTestWebApp to retrieve data from a database table.

Now you’re ready to use the same Java Persistence API and Visual Web Table component to add, update, and delete database table rows. For this to work, you add additional methods to the MyTestModelApp UserController class. You also modify the MyTestWebApp page that displays the Table component, adding functionality that enables user interaction and improves the table display.

Let's start by modifying the code in MyTestModelApp. Then, we'll show you how to modify the page in MyTestWebApp. We also explain the code you need to add to different Button component handlers so that everything works as intended.

 

Modify the Java Database Access Class

 

Recall that the UserController class in the MyTestModelApp project contained code that did some set up work and returned the data in the database table as an array. The UserController set up code called the EntityManagerFactory to create an EntityManager object. Then, it invoked the createQuery method on the EntityManager to construct a Java Persistence query that selected the rows from the Users database table. Now you need to add three methods to the UserController class:

  1. An addUser method to add records to the Users table.
  2. A removeUser method to remove records from the table.
  3. An updateUser method to modify records in the table.

First, add the addUser method to the UserController class. Double click the UserController.java and the source code file will be opened in the editor. Add the method after the getUsers method.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

The addUser method relies on methods from the EntityManager and EntityTransaction interfaces. Specifically, it establishes a transaction context by calling getTransaction().begin(). From within the transaction context, it uses the EntityManager persist method to make the user entity instance persistent, then commits the transaction, which writes the data to the database table and ends the transaction context.

 

public boolean addUser(Users users) {

  EntityManager em = getEntityManager();

   try{

     em.getTransaction().begin();

     em.persist(users);

     em.getTransaction().commit();

   } finally {

    em.close();

    return false;

   }

}

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Next, add the removeUser code to UserController to remove a record. Similar to the addUser method, this method establishes a transaction context, uses the primary key to locate the database table row that matches the entity to be deleted, then removes that entity instance. The commit call completes the removal and ends the transaction.

public boolean removeUser(Users users) {

        EntityManager em = getEntityManager();

        try {

            em.getTransaction().begin();

            Users userx = em.find(Users.class, users.getStudentId());

            em.remove(userx);

            em.getTransaction().commit();

        } finally {

            em.close();

            return false;

        }

    }

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Last, add the updateUser method to update a record. Similar to the previous two methods, the updateUser method does its work within the context of a transaction. It uses the primary key to find the matching entity instance, then invokes the get and set methods from the Users class to make the necessary changes to the table columns (Name, email address, and password), and commits the changes to end the transaction.

public boolean updateUser(Users users) {

        EntityManager em = getEntityManager();

        try {

            em.getTransaction().begin();

            Users userx = em.find(Users.class, users.getStudentId());

            userx.setName(users.getName());

            userx.setContactNo(users.getContactNo());

            userx.setEmail(users.getEmail());

            em.getTransaction().commit();

        } finally {

            em.close();

            return false;

        }

    }

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Use the Format from the context menu to format the added codes.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Modify the Web Page Design

 

After adding the code to the TheModelApp UserController class, you are ready to change the Page1 web page in the TheWebApp project. Changes include enhancing the Table component display, adding other components to the page, and customizing some of the page component code.

Start by enhancing the page and Table component display. The binding example in the first tutorial created a page and Table component that was rather minimal in appearance and functionality. Since that example only demonstrated the steps to display database data retrieved with the Java Persistence API, a bare-bones display was sufficient. Now we show you how to use the Visual Web features to create a web page and a Table component that more closely approximates that of a “real world” application.

In brief, you add three buttons (Add, Delete, and Update) to the page and place them so that they display beneath the table. You also add input fields so that users can enter a user name, password, and email address, if they are creating a new user entry or modifying an existing entry. You also add Add Record and Update Record buttons, so that users can indicate that they are adding or modifying the table rows.

You’ll also see how to use the Grid Panel components to align the input fields and buttons for a better presentation. Grid Panels are useful components for laying out text and other components on a page. When added to a page, they actually create a table-like container into which you add other components. Components added to a Grid Panel display from left to right (this horizontal direction can be reversed) and from top to bottom, and the Grid Panel can have from one to many columns plus as many rows as needed.

In addition, you’ll learn how to use the prerender method in conjunction with the Grid Panels to dynamically display portions of the page in the browser, depending on options chosen by the user. For example, when the page initially displays, you see only the table listing the users data stored in the database. The basic display remains the same when you delete an entry from the table; of course, the specified row is removed. But, when you indicate that you want to an entry or modify an existing entry, the page display changes to show the data fields you need to enter along with the corresponding two buttons. The prerender method code controls the page display according to boolean values set by the button action handlers.

Altogether, you place four Grid Panel components on the page, three of which will be nested within the first Grid Panel, and the other components (including the Table component, buttons, and input fields) are placed within these Grid Panels.

After placing all components on the page, you’ll see how to change the Table component’s display using the Table Layout functions.

 

Use Grid Panel Components to Control Page Display

 

Start by placing the Grid Panel components on the web page. The first Grid Panel you place on the page serves as a container for subsequent Grid Panel components plus other components.

Add a Grid Panel to serve as a component container. Open Page1 in the Designer window and drop a Grid Panel component onto the page.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

(The Grid Panel is in the Layout section of the Palette.) To help identify it, change the Grid Panel’s id property to mainContainer.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

This Grid Panel serves as a container for the other components on the page. You drop other components, such as other Grid Panels, buttons, and text fields, onto the Grid Panel and it helps control the alignment of these components.

By default, components added to a Grid Panel display from left to right based on the order they are added. If you find that this is not the case, check the setting of the Grid Panel's dir property (found in the Advanced section of the Properties sheet). The dir property direction should be set to Left to Right; if not, use the property's pull-down menu to change the setting.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Use the Navigator Window to Position Components

 

Next, add components to the mainContainer Grid Panel and use the hierarchical outline display in the Navigator window to reposition these components.

Begin by dropping a Table component onto the mainContainer Grid Panel. If this were a new page, you would drop a Table component onto the Grid Panel and then bind that Table component to the users array, just as you did previously. Since you already have a Table component bound to the users array on the page, you can instead use the Navigator window to move the Table component onto the Grid Panel.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Generally, the Navigator window provides an easy-to-use mechanism for accessing and moving components on a page, especially since the Navigator window displays all components on a page regardless of the component’s visibility on the page. It’s important to keep this in mind, since a number of components are not explicitly visible when added to a page.

You can drop a new Table component directly on the Grid Panel in the Design window. If you do so, be sure that the Grid Panel is highlighted before you drop the component. You can place the Table component already on the page onto mainContainer by dragging it within the Navigator window and dropping it on the Grid Panel. The previous Figure illustrates dragging table1 and placing it over the Grid Panel mainContainer, which is then highlighted. After dropping table1, the Navigator display changes to show that table1 is within mainContainer. The display on the page changes, too.

 

Add Remaining Components to Page

 

Now, add a Grid Panel for the Add, Delete, and Update buttons, then the Button components themselves. Add a second Grid Panel to the page and place three buttons (Add, Delete, and Update) in that panel. Be sure to drop this new Grid Panel on the right of the mainContainer. Set the id property for this Grid Panel to buttonPanel.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Since the three buttons should line up horizontally, use the buttonPanel Properties sheet to set the columns property to 1.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Then, drop three buttons on the buttonPanel and set their id and text properties as shown here. These buttons should be arranged vertically.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Add a Grid Panel for the user input fields, then the labels and input fields themselves. Drop a third Grid Panel below the buttonPanel. Set its id property to addUpdatePanel and its columns property to two (2).

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Then add three Label and Text Field components to the addUpdatePanel, for the input fields user name, password, and email address. By dropping first a Label then a Text Field onto addUpdatePanel, the labels and their input fields should align horizontally in this two-column Grid Panel and each pair should align vertically with the table. Add the following Label and Text Field component pairs in this order.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

If you face a difficulty to rearrange those components directly in the Design page, use drag and drop through the Navigator. I found it is easier to use Navigator to rearrange those components in order.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

And set their respective text and id properties as shown:

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Add a Grid Panel for the Add Record and Update Record buttons, along with these two buttons. Drop this Grid Panel on below the addUpdatePanel.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots  

 

Set its property id to addUpdateButtonPanel and its columns property to two (2).

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Then add the following two buttons to it. Resize the width, too, to keep the buttons to the left side of the display. (You can change addUpdateButtonPanel’s width property in the Properties sheet, or use the mouse to resize the panel in the Design window.)

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Finally put the addUpdateButtonPanel into addUpdatePanel, arrange it below the Email Address: label. Use the navigator to drag and drop the addUpdatePanel into addUpdatePanel at the bottom.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Placing the addUpdateButtonPanel buttons within the addUpdatePanel keeps these two buttons with the three data input fields. Later, after we add code for the button action handlers, we will also customize the prerender method so that the contents of the addUpdatePanel (the three input fields and the panel with the add/update record buttons) display only when a user wants to add a record or modify an existing record. The addUpdatePanel will not display when the table listing all users appears on the page or when a user deletes a row from the table.

 

Customize Table Display Using Table Layout

 

Use the Table Layout function to change the Table component display.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Using the Table Layout dialog, you add a new column to the table display.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

When added, it is given a default column header text of tableColumn5. Change this text to Select To Delete. In addition, from the Component Type pull-down list, select Radio Button and remove the text in the Value Expression Field.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

The completed Page1 looks as shown in the following Figure. Notice that there is the last column filled with radio buttons.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Re-arrange the studentId column to the leftmost.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

We need to provide an ample space for the table. Go to the table properties page. Do not set the table’s Height. Click the ellipses on the Style rightmost.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Select <Not Set> for the Height in the Position setting.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Run your project to see the GUI in browser.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Add Logic for Button Components

 

Now that you have completed the design of the web page, you need to add logic to the application so that the various buttons work as intended. You need to:

 

 

Write Java Code for the Radio Buttons

 

You need to write some logic (Java code) to hold information about the radio button that is selected on Page1, and you place the code in the Page1.java file. This code relies on the TableSelectPhaseListener class, a utility class that is part of the JavaServer Faces event package (com.sun.webui.jsf.event). The utility class is specifically for radio button components, and you use its methods to select rows of a table. The methods return a selected Table row as a RowKey object, which is a retrievable representation of a data row table identifier.

 

With Page1 displayed in the Design window, click the Java tab to open the Java code in the source editor.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Add the code shown in Code Example 4 after the getApplicationBean1 method (the last code). After adding the code, click Fix Imports so that the IDE imports the two missing classes (RowKey and TableSelectPhaseListener) and fixes the errors.

 

    private TableSelectPhaseListener tablePhaseListener = new TableSelectPhaseListener();   

    public void setSelected(Object object) {

        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");

        if (rowKey != null) {

            tablePhaseListener.setSelected(rowKey, object);

        }

    }

   

    public Object getSelected(){

        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");

        return tablePhaseListener.getSelected(rowKey);

       

    }

   

    public Object getSelectedValue() {

        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");

        return (rowKey != null) ? rowKey.getRowId() : null;

       

    }

   

    public boolean getSelectedState() {

        RowKey rowKey = (RowKey)getValue("#{currentRow.tableRow}");

        return tablePhaseListener.isSelected(rowKey);

    }

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Add JavaScript Code to the JavaServer Page File

 

Now you add JavaScript code to Page1’s JavaServer Page (JSP) file. In the Design window, click the JSP tab to open the JSP page for editing.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Add the code shown in Code Example 5 to the Table component; that is, add it within the <webuijsf:table> tag.

<script>

  function initAllRows() {

   var table = document.getElementById("form1:table1");

   table.initAllRows();

  }

</script>

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

After you add the JavaScript code, switch to the Design view to verify the code. Notice that the Page1.jsp display in the Navigator window reflects the table bindings (the individual bindings to the columns of the Users database table plus the radio button that you added) along with the JavaScript you just inserted.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

The JSP code itself shows the details of the table bindings. (Note: If the Navigator window does not display the updated Page1.jsp, click the Window > Reset Windows option.)

 

Bind the Radio Button to the Table Component

 

The Table component must keep track of the current selected table row via the Radio Button (which you added to the table earlier). To do so, you use the Visual Web Properties Binding dialog to bind a property of the Radio Button to the current row value. When you complete the dialog, the IDE updates the JSP code for you. Here’s how to do this binding.

 

1.      Open the Properties Binding dialog for radioButton1 on Page1. Select and right click the radio button.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

2.      Or in the Navigator window, scroll down the Page1 tree until you find radioButton1 within the table. (To see the Navigator window, select the Design tab for Page1. If the Navigator window does not display, click the Window > Reset Windows option.) Right click the radioButton1 node and select Property Bindings from the context menu.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

3.      Use the Properties Binding dialog to set three properties, noted here. You need to click the All option to see these properties in the Set bindable property column. After setting the binding expression for each property, be sure to click the Apply button so that the new expression is saved to the JSP file.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

4.      Set the property selected to #{Page1.selected} in the New binding expression: field. Click selected in the Select bindable property column, then click selected in the Select binding target column. Click Apply when the New binding expression field shows the correct binding;

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

5.      The Current binding field should change to the new binding.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

When the bindings are completed properly, the Radio Button tag in the JSP file should look as follows:

<webuijsf:radioButton binding="#{Page1.radioButton1}" id="radioButton1" label="" name="#{Page1.radioButton1.id}"selected="#{Page1.selected}" selectedValue="#{Page1.selectedValue}"/>

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

There are some additional property bindings that you must do.

 

1.      You need to bind some properties for the table column in which the Radio Button has been placed. In our example, this is tableColumn1. Select that table column in the Navigator window (or click that column in the Design window), open the Properties Binding dialog from the context menu, and set two properties.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

2.      You have to manually enter these binding expressions. As before, click Apply after setting each property.

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

When completed, the JSP code for the tableColumn1 tag should look as follows:

<webuijsf:tableColumn binding="#{Page1.tableColumn1}" id="tableColumn1" onClick="setTimeout('initAllRows()', 0)" selectId="#{Page1.radioButton1.id}">

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

3.      Now, bind the selected property on the table’s table row group (tableRowGroup1 in our example) to selectedState. The new binding expression should be #{Page1.selectedState}, as shown in Figure 9.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

The JSP code for the tag tableRowGroup should be as follows:

<webuijsf:tableRowGroup binding="#{Page1.tableRowGroup1}" id="tableRowGroup1" rows="10" selected="#{Page1.selectedState}" sourceData="#{SessionBean1.users}" sourceVar="currentRow"

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Write Code for Button Handler Methods

 

You need to add some code to the Add and Update button action handlers in Page1 (these two buttons are in the buttonPanel.) Later, we cover the code you add to the action handler methods for the two buttons at the bottom of the page, the Add Record and Update Record buttons.

This code also requires two boolean variables, which you need to add when you update the button action handler methods. After setting up all the button action handlers, you need to add some custom code to the prerender method.

 

Create Boolean Variables

 

Add the two Boolean variables to the Page1.java source file. Call these variables addRequest and updateRequest and set both values to false. You should have the following statements in the source file.

 

private boolean addRequest = false;

private boolean updateRequest = false;

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Write Button Action Handler Methods

 

Add code to the Add button’s addButton_action method. The added code sets a flag (addRequest) to true to enable the addUpdatePanel, which contains the entry fields for user name, password, and email address. The prerender method uses these boolean values to determine its handling of the addUpdatePanel.

Open the button code in the Java source editor by double clicking the Add button on the page in the Design window. Add a line to the addButton_action method that sets addRequest to true. The action handler should look as follows:

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

public String addButton_action() {

  addRequest = true;

  return null;

    }

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Note: If you open the Java source file for Page1 by clicking the Java tab rather than double clicking the button, you will not see the button’s action handler method. When you double click the button, the IDE adds an empty method for the action handler as a convenience and you only need add the custom lines of code.

Double click the Update button to open the updateButton_action method and add the following code. As with the addButton action handler, this code sets the boolean updateRequest to true so that the addUpdatePanel is enabled. The action handler should look as follows:

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

public String updateButton_action() {

  updateRequest = true;

  return null;

}

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Now, add code to the Delete button action handler so that when the button is clicked, the selected row from the table is deleted from the database. This code first obtains the selected RowKey from the tableRowGroup1. It uses the RowKey index to identify and obtain the corresponding row within the Users table. It then invokes the UserController.removeUser method, passing it the row identifier, and removeUser removes the selected row from the database. Most likely you will need to use the Fix Imports function after adding this code to the Page1.java file. Double click the Delete button and add the following code.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

public String deleteButton_action() {

        if (getTableRowGroup1().getSelectedRowsCount() > 0){

          RowKey[] selectedRowKeys = getTableRowGroup1().getSelectedRowKeys();

          Users[] users = getSessionBean1().getUsers();

          int rowId = Integer.parseInt(selectedRowKeys[0].getRowId());

          Users user = users[rowId];

          // Remove the Entity from the database using UserController

          UserController userController = new UserController();

          userController.removeUser(user);

        }

        return null;

}

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

-------------------------------------------------------------------------------------------------------------------------

 

----------------------------------------------------------------------------------------------------------------------------------

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Write Code to Create Entity Bean and Add to Database

 

Now you are ready to add code to the Add Record and Update Record action handler methods. The code for the Add Record action handler takes the data entered to the addUpdatePanel fields and creates a new entity bean encapsulating a row of data in the Users table. It then calls the UserController method addUser to add this entity bean data to the database. It also sets the boolean updateRequest to false. Later, you add code to the prerender method, which executes after the button action handler completes, that makes use of the boolean variables updateRequest and addRequest to determine the processing path to take.

Double click the Add Record button in the Design window to open the addRecordButton action handler in the Java source editor.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Then, add the following code to the method. The complete method should look as follows:

public String addRecordButton_action() {

        // Create a new User Entity

        Users newUser = new Users();

        newUser.setName((String) userNameField.getText());

        newUser.setContactNo((String) contactnoField.getText());

        newUser.setEmail((String) emailAddressField.getText());

        // Add the new Entity to the database using UserController

        UserController userController = new UserController();

        userController.addUser(newUser);

        updateRequest = false;

        return null;

    }

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Write Code to Update Database Record

 

You add code to the Update Record button’s action handler to update an existing record in the database. The action handler takes the data entered by the user in the fields of the addUpdatePanel and writes that data to the database record.

Double click the Update Record button to open the updateRecordButton_action action handler in the Java source editor and add the following code to the action handler. The added code first obtains the Users entity bean using the current selection in the table. It updates the Users fields with data entered in the addUpdatePanel fields, and then calls the UserController.updateUser method to update the database data with the entity bean data.

 

 

The completed action handler should look as follows:

 

    public String updateRecordButton_action() {

        // Create a new Users Entity

        RowKey[] selectedRowKeys = getTableRowGroup1().getSelectedRowKeys();

        Users[] users = getSessionBean1().getUsers();

        int rowId = Integer.parseInt(selectedRowKeys[0].getRowId());

        Users user = users[rowId];

        user.setName((String) userNameField.getText());

        user.setContactNo((String) contactnoField.getText());

        user.setEmail((String) emailAddressField.getText());

        // Update the database table data using UserController

        UserController userController = new UserController();

        userController.updateUser(user);

        addRequest = false;

        return null;

    }

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Modify prerender Method to Control Page Display

 

The prerender method on the page sets up any custom parameters for the page display and is invoked before the page is displayed. The following code, which you add to the prerender method, uses the boolean values addRequest and updateRequest to determine whether to show or hide the addUpdatePanel. It also updates the display of the user’s data based on whether modifications or data additions occur.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

public void prerender() {

        if (addRequest) {

            addUpdatePanel.setRendered(true);

            addRecordButton.setRendered(true);

            updateRecordButton.setRendered(false);

            userNameField.setText("");

            contactnoField.setText("");

            emailAddressField.setText("");

        } else if (updateRequest) {

            if (getTableRowGroup1().getSelectedRowsCount() > 0) {

                // Get the data from the selected Entity and update the fields

                RowKey[] selectedRowKeys = getTableRowGroup1().getSelectedRowKeys();

                Users[] users = (Users[]) getSessionBean1().getUsers();

                int rowId = Integer.parseInt(selectedRowKeys[0].getRowId());

                Users user = users[rowId];

                userNameField.setText(user.getName());

                contactnoField.setText(user.getContactNo());

                emailAddressField.setText(user.getEmail());

                addUpdatePanel.setRendered(true);

                addRecordButton.setRendered(false);

                updateRecordButton.setRendered(true);

            }

        } else {

            addUpdatePanel.setRendered(false);

        }

        // Refresh the users data array in the session bean to show

        // the newly added data or modified data in the Table Component

        getSessionBean1().updateUsers();

    }

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Run the Application

 

You are now ready to build and run the TestWebApp application. Right click TestWebApp in the Projects window and select Run Project.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

When the page opens in the browser, the display is very much like what you expect for an enterprise-level application.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

You can modify information for existing records, plus add new records and delete existing records. The page display changes depending on the buttons you selected.

 

Testing the Application

 

First of all, let try adding a new record. Click the Add button.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Fill-in the name, contact no and email address for new user and then click the Add Record button.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

New record has been added as shown in the following Figure.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Next, select the radio button for the 87003 and click the Update button. Do some editing on the name and email address and then click the Update Record button.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Finally, using the Delete feature. Select row by selecting the radio button (for example 87004 has been selected in the following Figure) and then click Delete button.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Printing The Table Data Using CSS

 

Obviously we can use a plain java code, java script and CSS for table printing. Keep in mind that JSF table don’t have printing method something like JTable. In this tutorial we will use CSS because every browser already has printing features. What we need is to format the browser printing pages removing the unwanted components.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

.noprint{

    display: none;

}

 

or

 

.noprint{

    visibility: hidden;

}

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Drag and drop the Link component onto the Page1.jsp while in Design mode. Take note that you can't see the Link in the design canvas. Find it in the Navigator and select it, this will launch its Properties page.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

In the Properties page, by default, the link was set to the css file. You can change to other file types as well. Click the ellipses for the URL.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Select the print.css that we have just created and click the OK.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Next set the media to print.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Well, open the JSP page, the added link can be seen as shown below.

<webuijsf:link binding="#{Page1.link2}" id="link2" media="print" url="/resources/print.css"/>

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Finally, any component that we do not want to appear in the print feature of the browsers we need to add the following code in the JSP page for every component.

 

styleClass="noprint"

 

The following line of codes shows how to hide the JSF button and label components.

<webuijsf:button styleClass="noprint" actionExpression="#{Page1.updateButton_action}" binding="#{Page1.updateButton}" id="updateButton" text="Update"/>

<webuijsf:label styleClass="noprint" binding="#{Page1.label1}" id="label1" text="Name:"/>

In our case, the following code (Page1.jsp), we hide all the label and the text field components from the browser's print feature display. In the final printing output, we hide all the JSF component except the table.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Testing the Table Printing Feature

 

After removing all the un-needed components except the table, re-run the project and invoke the Browser print menu (or print preview).

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

The following is the print preview of the Firefox Browser.

 

Step-by-step tutorial on MySQL database access and Java web application using JSP, JPA and JSF on NetBeans screenshots

 

Keep in mind that the normal way to print the table actually through a link or button. In this case we need to transfer the browser printing feature codes to a link or button and the browser supposed to be open in new window. Well, that all.

 

 

 

 

 

 

 

 

 

 


 

< Using JPA and JSF ver 2 (MySQL) | Main | Steps on Moving NetBeans Project >