[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 632
  • Last Modified:

Add paging to dynamically created table.

I use this code in my site :

<table id="productTable">

        <c:forEach var="product" items="${categoryProducts}" varStatus="iter">

            <tr class="${((iter.index % 2) == 0) ? 'lightBlue' : 'white'}">
                <td>
                    <img src="${initParam.productImagePath}${product.name}.png"
                         alt="${product.name}">
                </td>

                <td>
                    ${product.name}
                    <br>
                    <span class="smallText">${product.description}</span>
                </td>

                <td>&euro; ${product.price}</td>

                <td>
                    <form action="addToCart" method="post">
                        <input type="hidden"
                               name="productId"
                               value="${product.id}">
                        <input type="submit"
                               name="submit"
                               value="add to cart">
                    </form>
                </td>
            </tr>

        </c:forEach>

    </table>

Open in new window


With this code I display some records from a database.
How can I add paging to this table?
Thank you.
0
skiabox
Asked:
skiabox
  • 5
  • 2
2 Solutions
 
rrzCommented:
I pieced together some of my old code with what you have here. Please try it to see if it works.
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="totalCount" scope="session" value="${fn:length(categoryProducts)}"/>
<c:set var="perPage" scope="session"  value="10"/>
<c:set var="pageStart" value="${param.start}"/>
<c:if test="${empty pageStart or pageStart < 0}">
       <c:set var="pageStart" value="0"/>
</c:if>
<c:if test="${totalCount < pageStart}">
       <c:set var="pageStart" value="${pageStart - 10}"/>
</c:if>
        <a href="?start=${pageStart - 10}"><<</a>${pageStart + 1} - ${pageStart + 10} <a href="?start=${pageStart + 10}">>></a>
<table id="productTable">

        <c:forEach var="product" items="${categoryProducts}" varStatus="iter" 
                   begin="${pageStart}" end="${pageStart + perPage - 1}">

            <tr class="${((iter.index % 2) == 0) ? 'lightBlue' : 'white'}">
                <td>
                    <img src="${initParam.productImagePath}${product.name}.png"
                         alt="${product.name}">
                </td>

                <td>
                    ${product.name}
                    <br>
                    <span class="smallText">${product.description}</span>
                </td>

                <td>&euro; ${product.price}</td>

                <td>
                    <form action="addToCart" method="post">
                        <input type="hidden"
                               name="productId"
                               value="${product.id}">
                        <input type="submit"
                               name="submit"
                               value="add to cart">
                    </form>
                </td>
            </tr>

        </c:forEach>

    </table>

Open in new window

0
 
skiaboxAuthor Commented:
Thank you for the nice code but I get the following error :

java.lang.NumberFormatException: For input string: "start=4"

Here is the complete code of the page :

<%--
    Document   : category
    Created on : May 21, 2010, 12:20:23 AM
    Author     : tgiunipero
--%>


<div id="categoryLeftColumn">

    <c:forEach var="category" items="${categories}">

        <c:choose>
            <c:when test="${category.name == selectedCategory.name}">
                <div class="categoryButton" id="selectedCategory">
                    <span class="categoryText">
                        ${category.name}
                    </span>
                </div>
            </c:when>
            <c:otherwise>
                <a href="category?${category.id}" class="categoryButton">
                    <span class="categoryText">
                        ${category.name}
                    </span>
                </a>
            </c:otherwise>
        </c:choose>

    </c:forEach>

</div>

<div id="categoryRightColumn">

    <p id="categoryTitle">${selectedCategory.name}</p>
    
    <c:set var="totalCount" scope="session" value="${fn:length(categoryProducts)}"/>
    <c:set var="perPage" scope="session"  value="4"/>
    <c:set var="pageStart" value="${param.start}"/>
    <c:if test="${empty pageStart or pageStart < 0}">
       <c:set var="pageStart" value="0"/>
    </c:if>
    <c:if test="${totalCount < pageStart}">
       <c:set var="pageStart" value="${pageStart - 4}"/>
    </c:if>
        <a href="?start=${pageStart - 4}"><<</a>${pageStart + 1} - ${pageStart + 4} <a href="?start=${pageStart + 4}">>></a>

    <table id="productTable">

        <c:forEach var="product" items="${categoryProducts}" varStatus="iter"
                   begin="${pageStart}" end="${pageStart + perPage - 1}">

            <tr class="${((iter.index % 2) == 0) ? 'lightBlue' : 'white'}">
                <td>
                    <img src="${initParam.productImagePath}${product.name}.png"
                         alt="${product.name}">
                </td>

                <td>
                    ${product.name}
                    <br>
                    <span class="smallText">${product.description}</span>
                </td>

                <td>&euro; ${product.price}</td>

                <td>
                    <form action="addToCart" method="post">
                        <input type="hidden"
                               name="productId"
                               value="${product.id}">
                        <input type="submit"
                               name="submit"
                               value="add to cart">
                    </form>
                </td>
            </tr>

        </c:forEach>

    </table>
</div>

Open in new window

0
 
skiaboxAuthor Commented:
There is also an underlying servlet.
Your code produces the following url :
http://localhost:8080/AffableBean/category?start=4

And the underlying controller servlet cannot handle this.
Here is the code of the controller servlet :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import cart.ShoppingCart;
import entity.Category;
import entity.Product;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import session.CategoryFacade;
import session.OrderManager;
import session.ProductFacade;
import validate.Validator;

/**
 *
 * @author tgiunipero
 */
@WebServlet(name = "Controller",
            loadOnStartup = 1,
            urlPatterns = {"/category",
                           "/addToCart",
                           "/viewCart",
                           "/updateCart",
                           "/checkout",
                           "/purchase",
                           "/chooseLanguage"})
public class ControllerServlet extends HttpServlet {

    private String surcharge;

    @EJB
    private CategoryFacade categoryFacade;
    @EJB
    private ProductFacade productFacade;
    @EJB
    private OrderManager orderManager;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

        super.init(servletConfig);

        // initialize servlet with configuration information
        surcharge = servletConfig.getServletContext().getInitParameter("deliverySurcharge");

        // store category list in servlet context
        getServletContext().setAttribute("categories", categoryFacade.findAll());
    }

    /**
     * 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 {

        String userPath = request.getServletPath();
        HttpSession session = request.getSession();
        Category selectedCategory;
        Collection<Product> categoryProducts;

        // if category page is requested
        if (userPath.equals("/category")) {

            // get categoryId from request
            String categoryId = request.getQueryString();

            if (categoryId != null) {

                // get selected category
                selectedCategory = categoryFacade.find(Short.parseShort(categoryId));

                // place selected category in session scope
                session.setAttribute("selectedCategory", selectedCategory);

                // get all products for selected category
                categoryProducts = selectedCategory.getProductCollection();

                // place category products in session scope
                session.setAttribute("categoryProducts", categoryProducts);
            }


        // if cart page is requested
        } else if (userPath.equals("/viewCart")) {

            String clear = request.getParameter("clear");

            if ((clear != null) && clear.equals("true")) {

                ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
                cart.clear();
            }

            userPath = "/cart";


        // if checkout page is requested
        } else if (userPath.equals("/checkout")) {

            ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

            // calculate total
            cart.calculateTotal(surcharge);

            // forward to checkout page and switch to a secure channel


        // if user switches language
        } else if (userPath.equals("/chooseLanguage")) {
            // TODO: Implement language request

        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 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 {

        String userPath = request.getServletPath();
        HttpSession session = request.getSession();
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        Validator validator = new Validator();

        // if addToCart action is called
        if (userPath.equals("/addToCart")) {

            // if user is adding item to cart for first time
            // create cart object and attach it to user session
            if (cart == null) {

                cart = new ShoppingCart();
                session.setAttribute("cart", cart);
            }

            // get user input from request
            String productId = request.getParameter("productId");

            if (!productId.isEmpty()) {

                Product product = productFacade.find(Integer.parseInt(productId));
                cart.addItem(product);
            }

            userPath = "/category";


        // if updateCart action is called
        } else if (userPath.equals("/updateCart")) {

            // get input from request
            String productId = request.getParameter("productId");
            String quantity = request.getParameter("quantity");
            
            boolean invalidEntry = validator.validateQuantity(productId, quantity);
            
            if (!invalidEntry)
            {
                Product product = productFacade.find(Integer.parseInt(productId));
                cart.update(product, quantity);
            }
            
            userPath = "/cart";


        // if purchase action is called
        } else if (userPath.equals("/purchase")) {
            //Implement purchase action
            if (cart != null)
            {
                //extract user data from request
                String name = request.getParameter("name");
                String email = request.getParameter("email");
                String phone = request.getParameter("phone");
                String address = request.getParameter("address");
                String cityRegion = request.getParameter("cityRegion");
                String ccNumber = request.getParameter("creditcard");
                
                //validate user data
                boolean validationErrorFlag = false;
                validationErrorFlag = validator.validateForm(name, email, phone, address, cityRegion, ccNumber, request);
                
                //if validation error found, return user to checkout
                if (validationErrorFlag == true)
                {
                    request.setAttribute("validationErrorFlag", validationErrorFlag);
                    userPath = "/checkout";
                }
                else    //otherwise, save order to database
                    {
                
                    int orderId = orderManager.placeOrder(name, email, phone, address, cityRegion, ccNumber, cart);
                
                        //if order processed successfully send user to confirmation page
                        if (orderId != 0)
                        {
                            //dissociate shopping cart from session
                            cart = null;
                            
                            //end session
                            session.invalidate();
                            
                            //get order details
                            Map orderMap = orderManager.getOrderDetails(orderId);
                            
                            //place order details in request scope
                            request.setAttribute("customer", orderMap.get("customer"));
                            request.setAttribute("products", orderMap.get("products"));
                            request.setAttribute("orderRecord", orderMap.get("orderRecord"));
                            request.setAttribute("orderedProducts", orderMap.get("orderedProducts"));
                            
                            userPath = "/confirmation";
                        }
                        else //otherwise, send back to checkout page and display error
                            {
                                userPath = "/checkout";
                                request.setAttribute("orderFailureFlag", true);
                            }
                    }
            }
            
        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

Open in new window

0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
rrzCommented:
There is no need to call the controller when clicking on paging links.  The links should just call the same page to re-display the table. If the page is  category.jsp , then you should try using  
 <a href="category.jsp?start=${pageStart - 4}"><<</a>${pageStart + 1} - ${pageStart + 4} <a href="?start=${pageStart + 4}">>></a>
0
 
skiaboxAuthor Commented:
Every query string that uses category.jsp is handled my the controller.
I have the same problem like before.
I believe that we must write code in the controller too.
0
 
skiaboxAuthor Commented:
I found a solution based on your experience.
Thank you so much.

I just changed if (categoryId != null) with

if (categoryId != null && !categoryId.startsWith("start"))
0
 
skiaboxAuthor Commented:
So great support!
I love you guys!
:)
0

Featured Post

[Webinar] Kill tickets & tabs using PowerShell

Are you tired of cycling through the same browser tabs everyday to close the same repetitive tickets? In this webinar JumpCloud will show how you can leverage RESTful APIs to build your own PowerShell modules to kill tickets & tabs using the PowerShell command Invoke-RestMethod.

  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now