Thứ Hai, 21 tháng 7, 2014

Search Product By Name Using JSF

Đầu tiên ta sẽ tạo một project và sử dụng framework như dưới:


Đầu tiên để truy xuất vào cơ sở dữ liệu ta cần import sqljdbc4.jar sau đó tạo một class DataAccess đặt trong package "spbn.db" như dưới:

/*
 * 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 spbnj.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Nguyen Minh An
 */
public class DataAccess {

    public static Connection getConnection() throws SQLException {
        String url = "jdbc:sqlserver://localhost:1433;databaseName=DEMO_JSF";
        String username = "LUCKY";
        String password = "123456";

        try {
            Connection conn = null;
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn = DriverManager.getConnection(url, username, password);
            return conn;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

Tiếp đó ta sẽ tạo một trang jsf (xhtml) với tên index.xhtml như dưới:

<?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://xmlns.jcp.org/jsf/html"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:form>
            <h:inputText value="#{searchBean.keyword}"></h:inputText>
            <h:commandButton action="#{searchBean.searchByName}" value="Search"></h:commandButton>
            <ui:repeat value="#{searchBean.listproduct}" var="l">
                <h:outputLabel value="#{l.id}"></h:outputLabel>
                <h:outputLabel value="#{l.name}"></h:outputLabel>
                <h:outputLabel value="#{l.price}"></h:outputLabel>
            </ui:repeat>
        </h:form>

    </h:body>
</html>


Ta tạo một lớp Product với các thuộc tính và các phương thức get, set như dưới:

/*
 * 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 spbnj.entity;

/**
 *
 * @author Nguyen Minh An
 */
public class Product {
    private int id;
    private String name;
    private String price;

    public Product(int id, String name, String price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    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 getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
    
    
}

Tiếp đó ta tạo một lớp ProductManagement và phương thức để làm việc search dữ liệu trong database:

package spbnj.bussiness;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import spbnj.connection.DataAccess;
import spbnj.entity.Product;

/*
 * 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.
 */
/**
 *
 * @author Nguyen Minh An
 */
public class ProductManagement {

    public List<Product> listProduct;

    public List<Product> searchByName(String keyword) {
        try {
            listProduct = new ArrayList<>();
            Connection conn = DataAccess.getConnection();
            PreparedStatement ps = conn.prepareCall("SELECT * FROM PRODUCT WHERE name like '%" + keyword + "%'");
            ResultSet res = ps.executeQuery();
            while (res.next()) {                
                int id = res.getInt("id");
                String name = res.getString("name");
                String price = res.getString("price");
                Product p = new Product(id, name, price);
                listProduct.add(p);
            }
            return listProduct;
        } catch (SQLException ex) {
            Logger.getLogger(ProductManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

}

Tiếp đó ta tạo một lớp ManagedJSF Bean với tên là SearchBean như bên dưới.

/*
 * 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 spbnj.searchbean;

import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import spbnj.bussiness.ProductManagement;
import spbnj.entity.Product;

/**
 *
 * @author Nguyen Minh An
 */
@ManagedBean
@RequestScoped
public class SearchBean {

    private List<Product> listproduct;
    private String keyword;

    public SearchBean() {

    }

    public void searchByName() {
        listproduct = new ProductManagement().searchByName(keyword);
    }

    public List<Product> getListproduct() {
        return listproduct;
    }

    public void setListproduct(List<Product> listproduct) {
        this.listproduct = listproduct;
    }

    public String getKeyword() {
        return keyword;
    }

    public void setKeyword(String keyword) {
        this.keyword = keyword;
    }

}

Các bạn có thể tải Source Code ở đây

Nhận xét:
Mô hình khá đơn giản, dễ học, dễ hiểu, các thẻ có tên dễ dùng (tên biểu thị việc làm ví dụ như secret là input dưới type là mật khẩu, hay repeat thì là foreach).



Không có nhận xét nào:

Đăng nhận xét