Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Implement paging when having an underlying servlet controller

  1. #1
    Junior Member
    Join Date
    Jul 2011
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Implement paging when having an underlying servlet controller

    Here is the jsp code :

    <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>

    and here is the underlying 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();
            }
        }
     
    }

    How can I add paging to this page?
    Thank you.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,302
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Implement paging when having an underlying servlet controller

    How can I add paging to this page?
    Questions like this are very difficult to answer. First, you need to define 'paging'. Second, there are probably hundreds of ways to do what you wish - asking 'how do I do this' rarely leads to a productive discussion. Third, did you make an effort to try to do 'paging'...did you search the web? Lastly, I recommend reading the following link: http://catb.org/~esr/faqs/smart-questions.html

Similar Threads

  1. Web mvc controller - Brutos
    By urubu in forum Web Frameworks
    Replies: 6
    Last Post: July 28th, 2013, 12:09 PM
  2. Replies: 1
    Last Post: June 16th, 2011, 05:49 PM
  3. Replies: 1
    Last Post: June 15th, 2011, 01:27 PM
  4. collecting information/moving from servlet to servlet
    By CBird in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 1st, 2011, 06:04 PM
  5. creating a controller to allow instances to be created from keyboard
    By ss7 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: November 2nd, 2009, 12:30 PM