鍍金池/ 教程/ HTML/ JSF MySQL CURD實(shí)例
JSF數(shù)據(jù)表(h:dataTable)添加刪除
JSF <h:commandLink>標(biāo)簽
JSF應(yīng)用程序入門示例
JSF數(shù)據(jù)表(ui:repeat)創(chuàng)建表
JSF列表框
JSF數(shù)據(jù)表(h:dataTable)DataModel排序數(shù)據(jù)
JSF復(fù)合組件
JSF <h:inputText>標(biāo)簽
JSF表單組合框
JSF <h:messages>標(biāo)簽
JSF <h:message>標(biāo)簽
JSF轉(zhuǎn)換日期時(shí)間
JSF JDBC連接
JSF <h:inputHidden>標(biāo)簽
JSF多選列表框
JSF <h:inputSecret>標(biāo)簽
JSF自定義轉(zhuǎn)換器
JSF <f:ajax>標(biāo)簽
JSF生命周期
JSF可重定位資源
JSFJSF用戶界面組件模型
JSF <h:attribute>標(biāo)簽
JSF驗(yàn)證器標(biāo)簽
JSF驗(yàn)證字符串長(zhǎng)度
JSF轉(zhuǎn)換器標(biāo)簽
JSF托管bean(Managed Bean)
JSF值變化的事件
JSF UI組件示例
JSF MySQL CURD實(shí)例
JSF數(shù)據(jù)表(h:dataTable)排序數(shù)據(jù)
JSF <h:graphicImage>標(biāo)簽
JSF <f:convertNumber>標(biāo)簽
JSF教程
JSF托管Bean
JSF輸出腳本
JSF <h:outputText>標(biāo)簽
JSF操作事件
JSF驗(yàn)證正則表達(dá)式
JSF數(shù)據(jù)表(h:dataTable)行號(hào)
JSF <h:setPropertyActionListener>標(biāo)簽
JSF注入托管bean實(shí)例
JSF <h:commandButton>標(biāo)簽
JSF Web資源
JSF <h:inputFile>標(biāo)簽
JSF驗(yàn)證浮點(diǎn)數(shù)值范圍
JSF Facelets視圖
JSF是什么?
JSF Facelets模板
JSF的特性(特點(diǎn))
JSF自定義驗(yàn)證器類
JSF單選按鈕
JSF輸出樣式
JSF數(shù)據(jù)表(h:dataTable)更新數(shù)據(jù)
JSF HTML5友好標(biāo)記
JSF表單復(fù)選框(CheckBox)示例
JSF <h:form>標(biāo)簽
JSF Facelets技術(shù)介紹
JSF輸出格式化
JSF <h:inputtextarea>標(biāo)簽
JSF驗(yàn)證整數(shù)范圍
JSF <h:panelGrid>標(biāo)簽

JSF MySQL CURD實(shí)例

JSF提供豐富的工具和庫(kù)來(lái)創(chuàng)建應(yīng)用程序。 在這里,我們創(chuàng)建一個(gè)包含以下步驟的CRUD(增刪改查)應(yīng)用程序。

打開(kāi) NetBeans IDE,創(chuàng)建一個(gè)名稱為:jsf-curd 的 Web 工程,其目錄結(jié)構(gòu)如下所示 -

提示: 需要加入 mysql-connector-java Jar包。

使用文件說(shuō)明

我們?cè)陧?xiàng)目中使用了bootstrap CSS文件。點(diǎn)擊這里下載:
http://getbootstrap.com/dist/css/bootstrap.min.css

下載Mysql JDBC連接器JAR文件。點(diǎn)擊這里: http://dev.mysql.com/downloads/connector/j/5.1.html

這個(gè)JAR是將應(yīng)用程序連接到mysql數(shù)據(jù)庫(kù)所必需的。

此應(yīng)用程序包含用戶輸入表單,委托bean和響應(yīng)頁(yè)面,如以下步驟。

創(chuàng)建數(shù)據(jù)庫(kù)和表

我們使用mysql數(shù)據(jù)庫(kù)創(chuàng)建數(shù)據(jù)庫(kù)和表。

創(chuàng)建數(shù)據(jù)庫(kù)

使用以下SQL命令,創(chuàng)建一個(gè)數(shù)據(jù)庫(kù):test ;

create database test;

在這個(gè)數(shù)據(jù)中,創(chuàng)建一個(gè)表: users -

create table users(
    id int not null primary key auto_increment, 
    name varchar(100),   
    email varchar(50), 
    password varchar(20), 
    gender varchar(1), 
    address text
);

創(chuàng)建數(shù)據(jù)庫(kù)和表后,現(xiàn)在創(chuàng)建一個(gè)用戶表單來(lái)獲取輸入的用戶信息。

創(chuàng)建代碼文件

在這個(gè)項(xiàng)目中,要?jiǎng)?chuàng)建以下幾個(gè)代碼文件,它們分別是:

  • User.java - 委托Bean以及數(shù)據(jù)庫(kù)相關(guān)操作。
  • index.xhtml - 項(xiàng)目入口文件,用于列出用戶信息列表。
  • create.xhtml - 創(chuàng)建用戶信息的表單
  • edit.xhtml - 修改/編輯用戶信息的表單

User.java文件中的代碼如下所示 -

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yiibai;

/**
 *
 * @author Maxsu
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@RequestScoped
public class User {

    int id;
    String name;
    String email;
    String password;
    String gender;
    String address;
    ArrayList usersList;
    private Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
    Connection connection;

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
// Used to establish connection  

    public Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
        } catch (Exception e) {
            System.out.println(e);
        }
        return connection;
    }
// Used to fetch all records  

    public ArrayList usersList() {
        try {
            usersList = new ArrayList();
            connection = getConnection();
            Statement stmt = getConnection().createStatement();
            ResultSet rs = stmt.executeQuery("select * from users");
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setEmail(rs.getString("email"));
                user.setPassword(rs.getString("password"));
                user.setGender(rs.getString("gender"));
                user.setAddress(rs.getString("address"));
                usersList.add(user);
            }
            connection.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return usersList;
    }
// Used to save user record  

    public String save() {
        int result = 0;
        try {
            connection = getConnection();
            PreparedStatement stmt = connection.prepareStatement(
                    "insert into users(name,email,password,gender,address) values(?,?,?,?,?)");
            stmt.setString(1, name);
            stmt.setString(2, email);
            stmt.setString(3, password);
            stmt.setString(4, gender);
            stmt.setString(5, address);
            result = stmt.executeUpdate();
            connection.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        if (result != 0) {
            return "index.xhtml?faces-redirect=true";
        } else {
            return "create.xhtml?faces-redirect=true";
        }
    }
// Used to fetch record to update  

    public String edit(int id) {
        User user = null;
        System.out.println(id);
        try {
            connection = getConnection();
            Statement stmt = getConnection().createStatement();
            ResultSet rs = stmt.executeQuery("select * from users where id = " + (id));
            rs.next();
            user = new User();
            user.setId(rs.getInt("id"));
            user.setName(rs.getString("name"));
            user.setEmail(rs.getString("email"));
            user.setGender(rs.getString("gender"));
            user.setAddress(rs.getString("address"));
            user.setPassword(rs.getString("password"));
            System.out.println(rs.getString("password"));
            sessionMap.put("editUser", user);
            connection.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return "/edit.xhtml?faces-redirect=true";
    }
// Used to update user record  

    public String update(User u) {
//int result = 0;  
        try {
            connection = getConnection();
            PreparedStatement stmt = connection.prepareStatement(
                    "update users set name=?,email=?,password=?,gender=?,address=? where id=?");
            stmt.setString(1, u.getName());
            stmt.setString(2, u.getEmail());
            stmt.setString(3, u.getPassword());
            stmt.setString(4, u.getGender());
            stmt.setString(5, u.getAddress());
            stmt.setInt(6, u.getId());
            stmt.executeUpdate();
            connection.close();
        } catch (Exception e) {
            System.out.println();
        }
        return "/index.xhtml?faces-redirect=true";
    }
// Used to delete user record  

    public void delete(int id) {
        try {
            connection = getConnection();
            PreparedStatement stmt = connection.prepareStatement("delete from users where id = " + id);
            stmt.executeUpdate();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
// Used to set user gender  

    public String getGenderName(char gender) {
        if (gender == 'M') {
            return "Male";
        } else {
            return "Female";
        }
    }
}

index.xhtml文件中的代碼如下所示 -

<!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://xmlns.jcp.org/jsf/html"  
      xmlns:f="http://xmlns.jcp.org/jsf/core">  
    <h:head>  
        <title>User Details</title>  
        <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"></link>       
        <style type="text/css">  
            table {  
                border-collapse: collapse;  
                width: 100%;  
            }  
            th, td {  
                text-align: left;  
                padding: 8px;  
            }  

            tr:nth-child(even){background-color: #f2f2f2}  
            th {  
                background-color: #4CAF50;  
                color: white;  
            }  
        </style>  
    </h:head>  
    <h:body>  
        <h:form>  
            <center>  
                <h2><h:outputText value="User Records"/></h2>  
            </center>  
            <h:dataTable binding="#{table}" value="#{user.usersList()}" var="u"   
                         class="table table-striped table-hover table-bordered">  
                <h:column>  
                    <f:facet name="header">ID</f:facet>  
                    <h:outputText value="#{table.rowIndex + 1}"/>  
                </h:column>  
                <h:column>  
                    <f:facet name="header">User Name</f:facet>  
                    <h:outputText value="#{u.name}"/>  
                </h:column>  
                <h:column>  
                    <f:facet name="header">Email ID</f:facet>  
                    <h:outputText value="#{u.email}"/>  
                </h:column>  
                <h:column>  
                    <f:facet name="header">Password</f:facet>  
                    <h:outputText value="#{u.password}"/>  
                </h:column>  
                <h:column>  
                    <f:facet name="header">Gender</f:facet>  
                    <h:outputText value="#{user.getGenderName(u.gender)}"/>  
                </h:column>  
                <h:column>  
                    <f:facet name="header">Address</f:facet>  
                    <h:outputText value="#{u.address}"/>  
                </h:column>  
                <h:column>  
                    <f:facet name="header">Update</f:facet>  
                    <h:commandButton action = "#{user.edit(u.id)}" value="Update" class="btn btn-primary">  
                    </h:commandButton>  
                </h:column>  
                <h:column>  
                    <f:facet name="header">Delete</f:facet>  
                    <h:commandButton action = "#{user.delete(u.id)}" value="Delete" class="btn btn-danger">  
                    </h:commandButton>  
                </h:column>  
            </h:dataTable>  
            <center><h:commandButton action = "create.xhtml?faces-redirect=true"   
                                     value="Create New User" class="btn btn-success"></h:commandButton></center>  
        </h:form>  
    </h:body>  
</html>

create.xhtml文件中的代碼如下所示 -

<!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://xmlns.jcp.org/jsf/html"  
      xmlns:f="http://xmlns.jcp.org/jsf/core">  
    <h:head>  
        <title>User Registration Form</title>  
        <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"></link>   
    </h:head>  
    <h:body>  
        <h:form id="form" class="form-horizontal">  
            <div class="form-group">  
                <div class="col-sm-4"></div>  
                <div  class="col-sm-4">  
                    <h2 style="text-align: center">Provide Following Details</h2>  
                </div>  
            </div>  
            <hr/>  
            <div class="form-group">  
                <h:outputLabel for="username" class="control-label col-sm-4">User Name</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputText id="name-id" value="#{user.name}" class="form-control"   
                                 validatorMessage="User name is required">  
                        <f:validateRequired />  
                    </h:inputText>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="email" class="control-label col-sm-4">Your Email</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputText id="email-id" value="#{user.email}" class="form-control"   
                                 validatorMessage="Email Id is required">  
                        <f:validateRequired/>  
                    </h:inputText>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="password" class="control-label col-sm-4">Password</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputSecret id="password-id" value="#{user.password}" class="form-control"   
                                   validatorMessage="Password is required">  
                        <f:validateRequired/>  
                    </h:inputSecret>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="gender" class="control-label col-sm-4">Gender</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:selectOneRadio value="#{user.gender}" validatorMessage="Gender is required">  
                        <f:selectItem itemValue="M" itemLabel="Male" />  
                        <f:selectItem itemValue="F" itemLabel="Female" />  
                        <f:validateRequired/>  
                    </h:selectOneRadio>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="address" class="control-label col-sm-4">Address</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputTextarea value="#{user.address}" cols="50" rows="5" class="form-control"   
                                     validatorMessage="Address is required">  
                        <f:validateRequired/>  
                    </h:inputTextarea>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="col-sm-4"></div>  
                <div class="col-sm-4">  
                    <div class="col-sm-2">  
                        <h:commandButton value="Save" action="#{user.save()}" class="btn btn-success"   
                                         style="width: 80px;"></h:commandButton>  
                    </div>  
                    <div class="col-sm-1">  
                    </div>  
                    <div class="col-sm-2">  
                        <h:link outcome="index" value="View Users Record List" class="btn btn-primary" />  
                    </div>  
                </div>  
            </div>  
        </h:form>  
    </h:body>  
</html>

edit.xhtml文件中的代碼如下所示 -

<!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://xmlns.jcp.org/jsf/html"  
      xmlns:f="http://xmlns.jcp.org/jsf/core">  
    <h:head>  
        <title>Edit Your Record</title>  
        <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet"></link>   
    </h:head>  
    <h:body>  
        <h:form id="form" class="form-horizontal">  
            <div class="form-group">  
                <div class="col-sm-2"></div>  
                <h2 style="text-align: center" class="col-sm-4">Edit Your Record</h2>  
            </div>  
            <hr/>  
            <div class="form-group">  
                <h:outputLabel for="username" class="control-label col-sm-2">User Name</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputText id="name-id" value="#{editUser.name}" class="form-control"/>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="email" class="control-label col-sm-2">Your Email</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputText id="email-id" value="#{editUser.email}" class="form-control"/>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="password" class="control-label col-sm-2">Password</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputSecret id="password-id" value="#{editUser.password}" class="form-control"/>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="gender" class="control-label col-sm-2">Gender</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:selectOneRadio value="#{editUser.gender}">  
                        <f:selectItem itemValue="M" itemLabel="Male" />  
                        <f:selectItem itemValue="F" itemLabel="Female" />  
                    </h:selectOneRadio>  
                </div>  
            </div>  
            <div class="form-group">  
                <h:outputLabel for="address" class="control-label col-sm-2">Address</h:outputLabel>  
                <div class="col-sm-4">  
                    <h:inputTextarea value="#{editUser.address}" cols="50" rows="5" class="form-control"/>  
                </div>  
            </div>  
            <div class="form-group">  
                <div class="col-sm-2"></div>  
                <div class="col-sm-4">  
                    <center><h:commandButton value="Update" action="#{user.update(editUser)}"   
                                             class="btn btn-primary" style="width: 80px;"></h:commandButton></center>  
                </div>  
            </div>  
        </h:form>  
    </h:body>  
</html>

運(yùn)行實(shí)例

這是應(yīng)用程序的入口頁(yè)面(index.xhtml)。 運(yùn)行該項(xiàng)目后,會(huì)從mysql的test數(shù)據(jù)庫(kù)的users表中讀取數(shù)據(jù)來(lái)填充表格,在 Tomcat 啟動(dòng)完成后,打開(kāi)瀏覽器訪問(wèn)以下網(wǎng)址:

http://localhost:8084/jsf-curd/

如果程序沒(méi)有錯(cuò)誤或問(wèn)題,應(yīng)該可以看到以下結(jié)果 -

注: 因?yàn)檫@是第一次運(yùn)行, users 表中還沒(méi)有任何數(shù)據(jù)。

創(chuàng)建頁(yè)面:添加新的用戶記錄

您可以通過(guò)使用此應(yīng)用程序在用戶表中添加新的用戶記錄。

提交新的用戶信息,添加新記錄后,可以看到新用戶記錄如下 -

更新用戶記錄

在首頁(yè)中點(diǎn)擊對(duì)應(yīng)更新按鈕,并修改更新就好,如下所示 -