Lập trình chức năng quản lý chuyên mục Servlet 3 lớp trong java

Quản lý chuyên mục sản phẩm bằng java
Model cate.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 lavarel.Model; import java.sql.SQLException; /** * * @author Administrator */ public final class product_categoriesModel implements java.io.Serializable { private static final long serialVersionUID = 1L; public product_categoriesModel() { } public product_categoriesModel(java.sql.ResultSet rs) throws SQLException { this.setid(rs.getInt("id")); this.setname(rs.getString("name")); this.setdescription(rs.getString("description")); this.setcreated_at(rs.getTimestamp("created_at")); this.setupdated_at(rs.getTimestamp("updated_at")); this.setdeleted_at(rs.getTimestamp("deleted_at")); } private int _id; private String _name; private String _description; private java.sql.Timestamp _created_at; private java.sql.Timestamp _updated_at; private java.sql.Timestamp _deleted_at; public int getid() { return _id; } public product_categoriesModel setid(int value){ this._id = value; return this; } public String getname() { return _name; } public product_categoriesModel setname(String value){ if (value != null && value.length() > 255){ this._name = value.substring(0, 255); } else { this._name = value; } return this; } public String getdescription() { return _description; } public product_categoriesModel setdescription(String value){ if (value != null && value.length() > 0){ this._description = value.substring(0, 0); } else { this._description = value; } return this; } public java.sql.Timestamp getcreated_at() { return _created_at; } public product_categoriesModel setcreated_at(java.sql.Timestamp value){ this._created_at = value; return this; } public java.sql.Timestamp getupdated_at() { return _updated_at; } public product_categoriesModel setupdated_at(java.sql.Timestamp value){ this._updated_at = value; return this; } public java.sql.Timestamp getdeleted_at() { return _deleted_at; } public product_categoriesModel setdeleted_at(java.sql.Timestamp value){ this._deleted_at = value; return this; } }
Class DALcate.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 lavarel.DAL; import java.sql.*; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import lavarel.Utility.DatabaseUtility; import lavarel.Model.*; /** * * @author Administrator */ public final class product_categoriesDAL { private product_categoriesDAL() { } public static int insert(product_categoriesModel item) throws Exception { CallableStatement call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_Insert (?, ?, ?)}"); call.setInt("id", item.getid()); call.setString("name", item.getname()); call.setString("description", item.getdescription()); return DatabaseUtility.getInstance().executeUpdate(call); } public static int update(product_categoriesModel item) throws Exception { CallableStatement call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_Update (?, ?, ?)}"); call.setInt("id", item.getid()); call.setString("name", item.getname()); call.setString("description", item.getdescription()); return DatabaseUtility.getInstance().executeUpdate(call); } public static int insertOrUpdate(product_categoriesModel item) throws Exception { CallableStatement call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_InsertOrUpdate (?, ?, ?)}"); call.setInt("id", item.getid()); call.setString("name", item.getname()); call.setString("description", item.getdescription()); return DatabaseUtility.getInstance().executeUpdate(call); } public static int deleteByid(int id) throws Exception { CallableStatement call = DatabaseUtility.getInstance().getConnectionPool().getConnection().prepareCall("{CALL product_categories_DeleteByid (?)}"); call.setInt("id", id); return DatabaseUtility.getInstance().executeUpdate(call); } public static List<product_categoriesModel> selectAll() throws Exception { CallableStatement call = null; ResultSet rs = null; LinkedList<product_categoriesModel> list = new LinkedList<product_categoriesModel>(); try { call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_SelectAll}"); rs = DatabaseUtility.getInstance().executeQuery(call); while (rs.next()) { list.add(new product_categoriesModel(rs)); } } finally{ if(rs != null){ rs.close(); } if(call != null){ DatabaseUtility.getInstance().getConnectionPool().free(call.getConnection()); call.close(); } } return list; } public static product_categoriesModel selectByid(int id) throws Exception { CallableStatement call = null;ResultSet rs = null; LinkedList<product_categoriesModel> list = new LinkedList<product_categoriesModel>(); try { call = DatabaseUtility.getInstance().getConnectionPool().getConnection().prepareCall("{CALL product_categories_SelectByid (?)}"); call.setInt("id", id); rs = DatabaseUtility.getInstance().executeQuery(call); while (rs.next()) { list.add(new product_categoriesModel(rs)); }}finally{ if(rs != null){ rs.close();} if(call != null){ DatabaseUtility.getInstance().getConnectionPool().free(call.getConnection());call.close();}} return list.size() > 0 ? list.get(0) : null; } public static List<product_categoriesModel> selectByDynamic(String where, String orderby) throws Exception { CallableStatement call = null; ResultSet rs = null; LinkedList<product_categoriesModel> list = new LinkedList<product_categoriesModel>(); try { call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_SelectByDynamic (?, ?)}"); call.setNString("where", where); call.setNString("orderby", orderby); rs = DatabaseUtility.getInstance().executeQuery(call); while (rs.next()) { list.add(new product_categoriesModel(rs)); } } finally{ if(rs != null){ rs.close(); } if(call != null){ DatabaseUtility.getInstance().getConnectionPool().free(call.getConnection()); call.close(); } } return list; } public static List<product_categoriesModel> sort(List<product_categoriesModel> list, final String columnName, String orderby) { Collections.sort(list, new Comparator<product_categoriesModel>() { @Override public int compare(product_categoriesModel t1, product_categoriesModel t2) { if ("id".equals(columnName)) { return Integer.compare(t1.getid(), t2.getid()); } if ("name".equals(columnName)) { return t1.getname().compareToIgnoreCase(t2.getname()); } if ("description".equals(columnName)) { return t1.getdescription().compareToIgnoreCase(t2.getdescription()); } if ("created_at".equals(columnName)) { return t1.getcreated_at().compareTo(t2.getcreated_at()); } if ("updated_at".equals(columnName)) { return t1.getupdated_at().compareTo(t2.getupdated_at()); } if ("deleted_at".equals(columnName)) { return t1.getdeleted_at().compareTo(t2.getdeleted_at()); } return 0; } }); if ("DESC".equals(orderby.toUpperCase())) { Collections.reverse(list); } return list; } public static List<product_categoriesModel> search(String keyword) throws Exception { CallableStatement call = null; ResultSet rs = null; LinkedList<product_categoriesModel> list = new LinkedList<product_categoriesModel>(); try { call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_Search (?)}"); call.setNString("keyword", keyword); rs = DatabaseUtility.getInstance().executeQuery(call); while (rs.next()) { list.add(new product_categoriesModel(rs)); } } finally{ if(rs != null){ rs.close(); } if(call != null){ DatabaseUtility.getInstance().getConnectionPool().free(call.getConnection()); call.close(); } } return list; } public static List<product_categoriesModel> selectTop(int top, String where, String orderby) throws Exception { CallableStatement call = null; ResultSet rs = null; LinkedList<product_categoriesModel> list = new LinkedList<product_categoriesModel>(); try { call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_SelectTop (?, ?, ?)}"); call.setInt("top", top); call.setNString("where", where); call.setNString("orderby", orderby); rs = DatabaseUtility.getInstance().executeQuery(call); while (rs.next()) { list.add(new product_categoriesModel(rs)); } } finally{ if(rs != null){ rs.close(); } if(call != null){ DatabaseUtility.getInstance().getConnectionPool().free(call.getConnection()); call.close(); } } return list; } public static List<product_categoriesModel> paging(int page, int size, String where, String orderby) throws Exception { CallableStatement call = null; ResultSet rs = null; LinkedList<product_categoriesModel> list = new LinkedList<product_categoriesModel>(); try { call = DatabaseUtility.getInstance() .getConnectionPool().getConnection().prepareCall( "{CALL product_categories_Paging (?, ?, ?, ?)}"); call.setInt("page", page); call.setInt("size", size); call.setNString("where", where); call.setNString("orderby", orderby); rs = DatabaseUtility.getInstance().executeQuery(call); while (rs.next()) { list.add(new product_categoriesModel(rs)); } } finally{ if(rs != null){ rs.close(); } if(call != null){ DatabaseUtility.getInstance().getConnectionPool().free(call.getConnection()); call.close(); } } return list; } }
File Servlet cate.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 lavarel.Servlet; import javax.servlet.annotation.WebServlet; import java.io.*; import java.util.*; import lavarel.Utility.*; import javax.servlet.*; import javax.servlet.http.*; import lavarel.DAL.*; import lavarel.Model.*; /** * * @author Administrator */ @WebServlet(name = "product_categoriesServlet", urlPatterns = {"/admin/product_categories/*"}) public class product_categoriesServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final String INDEX_PAGE = "/admin/product_categories.jsp"; private final String ERROR_PAGE = "/error.jsp"; private final String IMAGE_SORT_DESC = "/public/templates/backend/img/admin/DESC.gif"; private final String IMAGE_SORT_ASC = "/public/templates/backend/img/admin/ASC.gif"; private String message = ""; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); try { if (!new LoginSession(request).isLogin(response)) { return; } String textSort = ""; String cmdDelete = request.getParameter("cmdDelete"); String[] cbxSelectOne = request.getParameterValues("cbxSelectOne"); String isDeleteMultiple = request.getParameter("isDeleteMultiple"); String cmdEdit = request.getParameter("cmdEdit"); String textAction = request.getParameter("textAction"); if (cmdDelete != null && !cmdDelete.isEmpty()) { deleteproduct_categories(request, response); } else if (cmdEdit != null && !cmdEdit.isEmpty()) { editproduct_categories(request, response); } else if (textAction != null && !textAction.isEmpty()) { updateproduct_categories(request, response); } else if (cbxSelectOne != null && cbxSelectOne.length > 0 && isDeleteMultiple != null && isDeleteMultiple.equals("true")) { deletelistproduct_categories(request, response); } List<product_categoriesModel> listproduct_categories = getListproduct_categories(request); //start sort String SortExpression = request.getParameter("SortExpression"); if (SortExpression != null && !SortExpression.isEmpty()) { textSort = (request.getParameter("textSort") == null ? "ASC" : request.getParameter("textSort")); textSort = (textSort.equals("ASC") ? "DESC" : "ASC"); listproduct_categories = sortproduct_categories(request, listproduct_categories, SortExpression, textSort); request.setAttribute("message", message); } //end sort DatabaseUtility.getInstance().getCache().put("listproduct_categories", listproduct_categories); message = new PageUtility<product_categoriesModel>().pagingAndDisplay(request, response, listproduct_categories, textSort); if (request.getAttribute("message") == null) { request.setAttribute("message", message); } RequestDispatcher dispath = getServletContext().getRequestDispatcher(INDEX_PAGE); dispath.forward(request, response); } catch (Exception ex) { PrintWriter out = response.getWriter(); out.println("Tìm thấy lỗi như sau :"+ex.getMessage()); // response.sendRedirect(ERROR_PAGE); } } private void editproduct_categories(HttpServletRequest request, HttpServletResponse response){ String mess = ""; StringBuilder str = new StringBuilder(); try { if (!new LoginSession(request).isLogin(response)) { return; } request.setAttribute("display", "block"); str.append("document.getElementById(\"textAction\").value = \"update\";"); String cmdEdit = request.getParameter("cmdEditError") == null ? request.getParameter("cmdEdit") : request.getParameter("cmdEditError"); request.setAttribute("item", product_categoriesDAL.selectByid(Integer.valueOf("0" + cmdEdit))); str.append("document.getElementById('textPageUpdate').value = '").append(request.getParameter("textPage")).append("';"); } catch (Exception e) { mess = e.getMessage(); } request.setAttribute("cmdEdit", str.toString()); request.setAttribute("message", mess); } private void updateproduct_categories(HttpServletRequest request, HttpServletResponse response){ try { if (!new LoginSession(request).isLogin(response)) { return; } request.setAttribute("display", "block"); product_categoriesModel item = new product_categoriesModel(); //item = (request.getParameter("textAction").equals("update") ? product_categoriesDAL.selectByid(Integer.valueOf("0" + cmdEdit)).get(0) : new product_categoriesModel()); item.setid(Integer.valueOf("0" + request.getParameter("txtid"))); item.setname(request.getParameter("txtname")); item.setdescription(request.getParameter("txtdescription")); int count = product_categoriesDAL.insertOrUpdate(item); if (count > 0) { request.setAttribute("display", "none"); request.setAttribute("message", count + " product_categories được cập nhật!"); DatabaseUtility.getInstance().getCache().put("listproduct_categories", product_categoriesDAL.selectAll()); } else { request.setAttribute("messageForm", "Lỗi!"); } } catch (Exception e) { editproduct_categories(request, response); request.setAttribute("messageForm", e.getMessage()); request.setAttribute("message", ""); } } private void deletelistproduct_categories(HttpServletRequest request, HttpServletResponse response){ String mess = ""; try { if (!new LoginSession(request).isLogin(response)) { return; } String[] cbxSelectOne = request.getParameterValues("cbxSelectOne"); int count = 0; for (String cmdDelete : cbxSelectOne) { count += product_categoriesDAL.deleteByid(Integer.valueOf("0" + cmdDelete)); } if (count > 0) { mess = count + " product_categories được xóa!"; DatabaseUtility.getInstance().getCache().put("listproduct_categories", product_categoriesDAL.selectAll()); } else { mess = "Lỗi!"; } } catch (Exception e) { mess = e.getMessage(); } request.setAttribute("message", mess); } private void deleteproduct_categories(HttpServletRequest request, HttpServletResponse response){ String mess = ""; try { if (!new LoginSession(request).isLogin(response)) { return; } String cmdDelete = request.getParameter("cmdDelete"); int count = product_categoriesDAL.deleteByid(Integer.valueOf("0" + cmdDelete)); if (count > 0) { mess = count + " product_categories được xóa!"; DatabaseUtility.getInstance().getCache().put("listproduct_categories", product_categoriesDAL.selectAll()); } else { mess = "Lỗi!"; } } catch (Exception e) { mess = e.getMessage(); } request.setAttribute("message", mess); } @SuppressWarnings("unchecked") private List<product_categoriesModel> getListproduct_categories(HttpServletRequest request) throws Exception { List<product_categoriesModel> list = null; String searchOneColumn = request.getParameter("searchOneColumn"); if (request.getParameterNames().hasMoreElements()) { if (searchOneColumn != null && !searchOneColumn.isEmpty()) { String searchOneValue = request.getParameter("searchOneValue"); if (searchOneValue == null || searchOneValue.isEmpty()) { list = product_categoriesDAL.selectAll(); } else { list = product_categoriesDAL.selectByDynamic(searchOneColumn + " = N'" + searchOneValue + "'", searchOneColumn); request.setAttribute("message", "Thông báo: Tìm kiếm theo " + request.getParameter("searchOneColumnName") + " \"" + searchOneValue + "\""); } } else if ((request.getParameter("imgbtnSearch.x") != null && request.getParameter("imgbtnSearch.y") != null) || (request.getParameter("imgbtnSearch_x") != null && request.getParameter("imgbtnSearch_y") != null)) { if (request.getParameter("textSearch") == null || request.getParameter("textSearch").isEmpty()) { list = product_categoriesDAL.selectAll(); } else { list = product_categoriesDAL.search(request.getParameter("textSearch")); request.setAttribute("message", "Thông báo: Tìm kiếm với từ khóa \"" + request.getParameter("textSearch") + "\""); } } else { list = (List<product_categoriesModel>) DatabaseUtility.getInstance().getCache().getIfPresent("listproduct_categories"); if (list == null){ list = product_categoriesDAL.selectAll(); } } } else { list = product_categoriesDAL.selectAll(); } return list; } private List<product_categoriesModel> sortproduct_categories(HttpServletRequest request, List<product_categoriesModel> list, String SortExpression, String textSort) { message = "Thông báo: \"" + request.getParameter("HeaderText") + "\" sắp xếp " + (textSort.equals("ASC") ? "tăng dần" : "giảm dần"); String img = "<input class=\"sort-img\" onclick=\"return false;\" type=\"image\" src=\"" + IMAGE_SORT_DESC + "\">"; img = (textSort.equals("ASC") ? "<input class=\"sort-img\" onclick=\"return false;\" type=\"image\" src=\"" + IMAGE_SORT_ASC + "\">" : img); request.setAttribute("imgSort", img); return product_categoriesDAL.sort(list, SortExpression, textSort); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }