28 September 2016

Pagination Jtable JSP Servlet JQuery Java Web - Next Previous Goto page Row count

Pagination Jatble JSP Servlet JQuery Java Web
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.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
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")) {
                    //Get list
                    int startPage = Integer.parseInt(request.getParameter("jtStartIndex"));
                    int pageSize = Integer.parseInt(request.getParameter("jtPageSize"));
                    shopList = dao.getAllShop(startPage, pageSize);
                    //Get total shop
                    int shopCount = dao.getUserCount();
                    
////                    Convert java Ojecb to Json
//                    JsonElement e = gson.toJsonTree(shopList, new TypeToken<List<Shop>>() {
//                    }.getType());
//                    JsonArray j = e.getAsJsonArray();
//                    String data = j.toString();
//                    //Return Json in the Format requied by Jtable plugin
//                    data = "{\"Result\":\"OK\",\"Records\":" + data + ",\"TotalRecordCount\":" + shopCount + "}";
//                    response.getWriter().print(data);
                    
                    JSONROOT.put("Result", "OK");
                    JSONROOT.put("Records", shopList);
                    JSONROOT.put("TotalRecordCount", shopCount);

                    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);
            }
        }
    }

}
Dao: 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 conn;
    private PreparedStatement stmt;

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

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

    public void deleteShop(String userId) {
        String deleteQuery = "DELETE FROM `product`.`shop` WHERE `id`=?;";
        try {
            stmt = conn.prepareStatement(deleteQuery);
            stmt.setString(1, userId);
            stmt.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 {
            stmt = conn.prepareStatement(updateQuery);
            stmt.setString(1, shop.getName());
            stmt.setString(2, shop.getDetail());
            stmt.setDouble(3, shop.getPrice());
            stmt.setString(4, shop.getImage());
            stmt.setString(5, shop.getId());
            stmt.executeUpdate();

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

    public List<Shop> getAllShop(int startIndex, int pageSize) {
        List<Shop> list = new ArrayList();

        String sql = "SELECT * FROM product.shop LIMIT ?,?";
        try {
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, startIndex);
            stmt.setInt(2, pageSize);
            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 int getUserCount() {
        int count = 0;
        String sql = "SELECT Count(*) as count FROM product.shop";
        try {
            stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                count = rs.getInt("count");
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        }
        return count;
    }
//    public static void main(String[] args) {
//        CrudDao c = new CrudDao();
//        System.out.println(c.getUserCount());
//    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang