/*
* 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 controller;
import dal.CategoryDAO;
import dal.ProductDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import model.Category;
import model.Product;
public class HomeController extends HttpServlet {
/**
* Processes requests for both HTTP GET
and POST
* 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");
final int PAGE_SIZE = 6;
List listCategories = new CategoryDAO().getAllCategories();
request.setAttribute("listCategories", listCategories);
int page = 1;
String pageStr = request.getParameter("page");
if (pageStr != null) {
page = Integer.parseInt(pageStr);
}
ProductDAO productDAO = new ProductDAO();
List listProducts = productDAO.getProductsWithPagging(page, PAGE_SIZE);
int totalProducts = productDAO.getTotalProducts();
int totalPage = totalProducts / PAGE_SIZE; //1
if (totalProducts % PAGE_SIZE != 0) {
totalPage += 1;
}
request.setAttribute("page", page);
request.setAttribute("totalPage", totalPage);
request.setAttribute("listProducts", listProducts);
request.getSession().setAttribute("urlHistory", "home");
request.getRequestDispatcher("home.jsp").forward(request, response);
}
//
/**
* Handles the HTTP GET
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 POST
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";
}//
}