27 September 2016

Insert Update Delete Jsp Servlet Java Web CRUD JTABLE JQuery NetBeans

Database mysql
Demo: Jtable
Type set: TYPE
 Insert - Add
 Update - Edit    id: 19
Delete

Delete All Checkbox

Add Library: //tải về
mysql-connector-java-5.1.38-bin.jar
gson-2.2.4.jar  //google-gson

CSS: //có trong project
jtable.css
jquery-ui-1.10.3.custom.css

JQuery: //có trong project
jquery-1.8.2.js
jquery-ui-1.10.3.custom.js
jquery.jtable.js
//Ở bài này phần lưu file pdf, excel và pagination chưa làm!
Tạo phân trang Pagination next previous go to pages
Đổi giao diện Theme Jtable 
Tạo thêm table Phone và List note chưa có thê sửa xóa

index.jsp
Java Web  2016
<!DOCTYPE>
<html>
    <head>
        <title>CRUD operations using jTable in J2EE</title>
        <!-- Include one of jTable styles. -->
        <link href="css/metro/blue/jtable.css" rel="stylesheet" type="text/css" />
        <link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
        <!-- Include jTable script file. -->
        <script src="js/jquery-1.8.2.js" type="text/javascript"></script>
        <script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
        <script src="js/jquery.jtable.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#StudentTableContainer').jtable({
                    title: 'Students List',
                    paging: true, //Enable paging
                    pageSize: 10, //Set page size (default: 10)
                    sorting: true, //Enable sorting
                    defaultSorting: 'id ASC',
                    selecting: true, //Enable selecting
                    multiselect: true, //Allow multiple selecting
                    selectingCheckboxes: true, //Show checkboxes on first column
                    selectOnRowClick: false, //Click row on check box
                    actions: {
                        listAction: 'Controller?action=list',
                        createAction: 'Controller?action=create',
                        updateAction: 'Controller?action=update',
                        deleteAction: 'Controller?action=delete'
                    },
                    toolbar: {
                            items: [{
                                icon: 'css/images/excel.png',
                                text: 'Export to Excel',
                                click: function () {
                                    //perform your custom job...
                                }
                            }, {
                                icon: 'css/images/pdf.png',
                                text: 'Export to Pdf',
                                click: function () {
                                    //perform your custom job...
                                }
                            }]
                    },
                    fields: {
                        id: {
                            title: 'ID Product',
                            width: '30%',
                            key: true,
                            list: true,
                            edit: true,
                            create: true
                        },
                        name: {
                            title: 'Name',
                            width: '30%',
                            edit: true
                        },
                        detail: {
                            title: 'Detail',
                            width: '30%',
                            type: 'textarea',
                            edit: true,
                            sorting: false //This column is not sortable!

                        },
                        price: {
                            title: 'Price',
                            width: '30%',
                            edit: true
                        },
                        image: {
                            title: 'Image',
                            width: '30%',
                            edit: true,
                            sorting: false //This column is not sortable!
                        }


                    },
                    //Register to selectionChanged event to hanlde events
                    selectionChanged: function () {
                        //Get all selected rows
                        var $selectedRows = $('#StudentTableContainer').jtable('selectedRows');

                        $('#SelectedRowList').empty();
                        if ($selectedRows.length > 0) {
                            //Show selected rows
                            $selectedRows.each(function () {
                                var record = $(this).data('record');
                                $('#SelectedRowList').append('<b>id</b>: ' + record.id + '<b> name</b>:' + record.name + '<br /><br />');
                            });
                        } else {
                            //No rows selected
                            $('#SelectedRowList').append('No row selected! Select rows to see here...');
                        }
                    },
                    rowInserted: function (event, data) {
                        if (data.record.name.indexOf('Andrew') >= 0) {
                            $('#StudentTableContainer').jtable('selectRows', data.row);
                        }
                    }
                });

                //Load student list from server
                $('#StudentTableContainer').jtable('load');

                //Delete selected students
                $('#DeleteAllButton').button().click(function () {
                    var $selectedRows = $('#StudentTableContainer').jtable('selectedRows');
                    $('#StudentTableContainer').jtable('deleteRows', $selectedRows);
                });
                $('#MyTableContainer').jtable('option', 'pageSize', 20);
            });
        </script>

    </head>
    <body>
        <div style="width: 80%; margin-right: 10%; margin-left: 10%; text-align: center;">
            <div id="StudentTableContainer"></div> <!--Output-->
            <div id="DeleteAllButton">Delete All</div><!--Button delete all-->
        </div>
    </body>
</html>
DBUtility.java
Java 2016
package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBUtility {

    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {
            String dbUrl = "jdbc:mysql://localhost:3306/product";
            try {
                Class.forName("com.mysql.jdbc.Driver");
                // set the url, username and password for the database
                connection = DriverManager.getConnection(dbUrl, "root", "1234567");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return connection;
        }
    }
//    Test Connect
//    public static void main(String[] args) {
//        System.out.println(getConnection());
//    }
}
Shop.java
Java Web  2016
package com.model;

public class Shop {

private String id;
private String name;
private String detail;
private Double price;
private String image;

    public Shop() {
    }

    public Shop(String id, String name, String detail, Double price, String image) {
        this.id = id;
        this.name = name;
        this.detail = detail;
        this.price = price;
        this.image = image;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public Double getPrice() {
        return price;
    }

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

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

//    public static void main(String[] args) {
//        Shop s = new Shop("1","Dai", "dd", 334.0 , "aaa");
//        System.out.println(s.getDetail());
//    }
   
}
CrudDao.java
Java Web  2016
package com.dao;

import com.jdbc.DBUtility;
import com.model.Shop;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


public class CrudDao {

    private Connection dbConnection;
    private PreparedStatement pStmt;

    public CrudDao() {
        dbConnection = DBUtility.getConnection();
    }

    public void addShop(Shop shop) {
        String insertQuery = "INSERT INTO product.shop (id, name, detail, price, image) VALUES (?,?,?,?,?)";
        try {
            pStmt = dbConnection.prepareStatement(insertQuery);
            pStmt.setString(1, shop.getId());
            pStmt.setString(2, shop.getName());
            pStmt.setString(3, shop.getDetail());
            pStmt.setDouble(4, shop.getPrice());
            pStmt.setString(5, shop.getImage());
            pStmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }

    public void deleteShop(String userId) {
        String deleteQuery = "DELETE FROM `product`.`shop` WHERE `id`=?;";
        try {
            pStmt = dbConnection.prepareStatement(deleteQuery);
            pStmt.setString(1, userId);
            pStmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }

    public void updateShop(Shop shop) {
        String updateQuery = "UPDATE `product`.`shop` SET `name`=?, `detail`=?, `price`=?, `image`=? WHERE `id`=?;";
        try {
            pStmt = dbConnection.prepareStatement(updateQuery);
            pStmt.setString(1, shop.getName());
            pStmt.setString(2, shop.getDetail());
            pStmt.setDouble(3, shop.getPrice());
            pStmt.setString(4, shop.getImage());
            pStmt.setString(5, shop.getId());
            pStmt.executeUpdate();

        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
    }

    public List<Shop> getAllShop() {
        List<Shop> list = new ArrayList();

        String sql = "SELECT * FROM product.shop";
        try {
            PreparedStatement stmt = dbConnection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {

                String id =rs.getString("id");
                String name = rs.getString("name");
                String detail = rs.getString("detail");
                Double price = rs.getDouble("price");
                String imag = rs.getString("image");
                
                Shop s = new Shop(id, name, detail, price, imag);
                list.add(s);
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
        return list;
    }
 
//    public static void main(String[] args) {
//        CrudDao c = new CrudDao();
//        System.out.println(c.getAllShop());
//    }
    
}

Servlet: Controller.java
Java Web  2016
package com.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.CrudDao;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.model.Shop;

public class Controller extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private HashMap<String, Object> JSONROOT = new HashMap<String, Object>();

    private CrudDao dao;

    public Controller() {
        dao = new CrudDao();
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        //Fix lỗi tiếng việt
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("utf-8");

        String action = request.getParameter("action");
        List<Shop> shopList = new ArrayList<Shop>();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        response.setContentType("application/json");

        if (action != null) {
            try {
                if (action.equals("list")) {
                    shopList = dao.getAllShop();

                    // Return in the format required by jTable plugin
                    JSONROOT.put("Result", "OK");
                    JSONROOT.put("Records", shopList);

                    // Convert Java Object to Json
                    String jsonArray = gson.toJson(JSONROOT);

                    response.getWriter().print(jsonArray);
                } else if (action.equals("create") || action.equals("update")) {
                    Shop shop = new Shop();
                    if (request.getParameter("id") != null) {
                        String id = request.getParameter("id");
                        shop.setId(id);
                    }

                    if (request.getParameter("name") != null) {
                        String name = request.getParameter("name");
                        shop.setName(name);
                    }

                    if (request.getParameter("detail") != null) {
                        String detail = request.getParameter("detail");
                        shop.setDetail(detail);
                    }

                    if (request.getParameter("price") != null) {
                        Double price = Double.parseDouble(request.getParameter("price"));
                        shop.setPrice(price);
                    }
                    
                    if (request.getParameter("image") != null) {
                        String image = request.getParameter("image");
                        shop.setImage(image);
                    }

                    if (action.equals("create")) {
                        // Create new record
                        dao.addShop(shop);
                    } else if (action.equals("update")) {
                        // Update existing record
                        dao.updateShop(shop);
                    }

                    // Return in the format required by jTable plugin
                    JSONROOT.put("Result", "OK");
                    JSONROOT.put("Record", shop);

                    // Convert Java Object to Json
                    String jsonArray = gson.toJson(JSONROOT);
                    response.getWriter().print(jsonArray);
                } else if (action.equals("delete")) {
                    // Delete record
                    if (request.getParameter("id") != null) {
                        String id = request.getParameter("id");
                        dao.deleteShop(id);

                        // Return in the format required by jTable plugin
                        JSONROOT.put("Result", "OK");

                        // Convert Java Object to Json
                        String jsonArray = gson.toJson(JSONROOT);
                        response.getWriter().print(jsonArray);
                    }
                }
            } catch (Exception ex) {
                JSONROOT.put("Result", "ERROR");
                JSONROOT.put("Message", ex.getMessage());
                String error = gson.toJson(JSONROOT);
                response.getWriter().print(error);
            }
        }
    }
}
Download zip import NetBeans
Bản 1 hoặc Bản 2

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang