Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 1 of 1
  1. #1
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Add items to JDBC db

    I had a servlet which was a list of items and included a jsp form to add new items/remove the current item. I am now using a database, and trying to get the add/remove functionality working. This is for extra credit on a homework, it's giving errors when I use the same .add and .remove. I'm guessing the methods to do this with JDBC are different, but can't find what they are.

    Here is my code from before:
    Code:
    package homework;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Vector;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class Controller extends HttpServlet {
    
        private List<DressBean> dresses = new Vector<DressBean>(5);
    
        @Override
        public void init() throws ServletException {
            dresses.add(new DressBean("Alfred Angelo Pleated Strapless Dress",
                    "Who says you can't wear a bridesmaid dress again? This dress hugs your curves in all the right places to give a slimming look. The strapless sweetheart neckline is elegant and perfect for any bridesmaid. This tea length dress is fully lined dress, back zip, and dry clean only and is available in sizes 2 - 20W and comes in all 20 colors.",
                    149.99, "aa.jpg")); //Image from http://s7d4.scene7.com/is/image/AlfredAngelo/?src=ir{AlfredAngeloRender/7231-600?resmode=sharp&sharpen=1}&wid=340
            dresses.add(new DressBean("David's Bridal Sleeveless Chiffon Dress",
                    "A 'must have' for your bridal party. This dress has a high neckline and keyhole detail on the back. Made from tafeta, this dress features an elastic waist to help flatter any figure. Designed at knee length it is fully lined with a back zip. This dress is available in canary, clover, malibu, and plum and is available in sizes 0 - 30W.",
                    149.0, "db.jpg")); //Image a screenshot from http://www.davidsbridal.com/Product_Sleeveless-Illusion-Neckline-Dress-with-Tie-Back-EJ3M4624_Bridal-Party-Bridesmaids-Short-Bridesmaid-Dresses
            dresses.add(new DressBean("Jenny Yoo Organza Strapless Dress",
                    "A whimsical and charming look that your bridesmaids will love. This dress is breathtaking with the addition of pick-up points at the skirt. Made from organza, it has optional spaghetti straps to make everyone comfortable. This dress is available in all 20 colors and sizes 2 to 20W and 8JB to 16JB.",
                    159.99, "jy.jpg")); //Image from https://a248.e.akamai.net/origin-cdn.volusion.com/epozq.muhxg/v/vspfiles/photos/1281-2T.jpg?1378951773
            dresses.add(new DressBean("Lela Rose Chiffon Strapless Dress with Cap Sleeves",
                    "This ravishing dress features a sweetheart neckline with cap sleeves. Available in floor length or tea length, it includes an optional rhinestone flower waistband. It is available in wheat, silver mist, copper, sunset, and guava in sizes 0 to 20W and maternity sizes.",
                    140.99, "lr.jpg")); //Image from http://s1.dessy.com/s/i/product/6225/6225-eggp-yawah.jpg
            dresses.add(new DressBean("Donna Morgan Strapless Satin Ballgown",
                    "Take a step into the old world with the satin ballgown style dress. The illusion neckline and flowered waistband add a unique twist to this dress that everyone will love. Available in dark pacific, cameo, bermuda blue, and carnation and sizes sizes 0 to 30W and 8JB to 16JB.",
                    188.99, "dm.jpg")); //Image from Take a step into the old world with the satin ballgown style dress. The illusion neckline and flowered waistband add a unique twist to this dress that everyone will love. Available in dark pacific, cameo, bermuda blue, and carnation and sizes sizes 0 to 30W and 8JB to 16JB.
        }
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            HttpSession session = request.getSession();
            String target = "/viewDresses.jsp"; //the JSP page which will be loaded
            int index = 0; //track the index used for the next/previous buttons
            Integer position = (Integer) session.getAttribute("position"); //retrieve the session data
            if (position != null) //if a session exists, loads the position
            {
                index = position.intValue();
            }
            String button = request.getParameter("button"); //for all form items with the name "button" set to var button
            String name = request.getParameter("style"); //for all form items with the name "style" set to var name
            String desc = request.getParameter("desc");//for all form items with the name "desc" set to var desc
            String sPrice = request.getParameter("price");//for all form items with the name "price" set to var price1
            String url = request.getParameter("image");//for all form items with the name "image" set to var url
            String removedMsg = "The requested item has been removed"; //Outputs a message notifiying the user the item was removed
    
            if (button == null || "".equals(button)) {
                // no button was pressed, so no action will be taken
            } else if ("Next".equals(button)) {
                index = index + 1;
                if (index >= dresses.size()) {
                    index = 0; //if last item in the list, loop back to first item when next button pressed
                }
            } else if ("Prev".equals(button)) {
                index = index - 1;
                if (index < 0) { //if first item in list, loop to end of list when previous button pushed
                    index = dresses.size() - 1;
                }
            } else if ("List".equals(button)) {
                target = "/dressList.jsp"; //Loads the dressList.jsp page 
                request.setAttribute("dresses", dresses);
            } else if ("Add Item".equals(button)) {
                target = "/add.jsp"; //Loads the add.jsp page to add new items
            } else if ("Submit".equals(button)) { //When submit is pressed on add.jsp
                if (sPrice != null && !sPrice.isEmpty()) {
                    Double price = Double.parseDouble(sPrice); //Converts the sPrice string to double
                    dresses.add(new DressBean(name, desc, price, url)); //Adds the new data to the dressBean
                } else {
                    sPrice = "n/a"; //If price is empty, set sPrice to n/a
                    dresses.add(new DressBean(name, desc, sPrice, url)); //Uses the method of dressBean with price as a string
                }
            } else if ("Remove Item".equals(button)) { //Removes the item currently being viewed from the list, outputs a message letting the user know
                DressBean currentItem = dresses.get(index);
                dresses.remove(currentItem);
                request.setAttribute("removedMsg", removedMsg);
            } else {
                //no other actions to take
            }
    
            //set the session with the info on currently viewing item
            session.setAttribute("position", new Integer(index));
            request.setAttribute("dress", dresses.get(index)); //sends the index of dress last viewed to the JSP
    
            ServletContext context = this.getServletContext(); //Returns reference to servlet context
            RequestDispatcher dispatcher = context.getRequestDispatcher(target); //Sets the target data to be sent the JSP
            dispatcher.forward(request, response); //Forwards the request
        }
    
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response); //Points to doGet, so same action will be taken whether loaded by POST or GET
        }
    }
    It is now giving an error for add and remove, "cannot find symbol method add(DressBean)" (same with .remove). Here is the new code

    Code:
    package homework;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    public class Controller extends HttpServlet {
    
        private DaoFactory factory;
    
        @Override
        public void init() throws ServletException {
            String basepath = this.getServletContext().getRealPath("/") + "WEB-INF"; //finds web-inf directory
            factory = new DaoFactory(basepath); //Sends the basepath to the DaoFactory and sets this object to var factory
            DaoPattern<DressBean> dao = factory.getDao("DB"); //DB oriented DAO
        }
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            HttpSession session = request.getSession(); //Sets the session variable
    
            String target = "/viewDresses.jsp"; //the JSP page which will be displayed when the servlet is loaded
    
            DressBean dress = (DressBean) session.getAttribute("dress");
            String basePath = this.getServletContext().getRealPath("/") + "WEB-INF";
            DaoPattern<DressBean> dao; //Gets the DressBean data
            ArrayList<DressBean> cart = (ArrayList<DressBean>) session.getAttribute("cart"); //Creating the arraylist for cart items
            dao = factory.getDao("DB"); //Gets the db data
            List<DressBean> allDresses;
    
            String button = request.getParameter("button"); //for all form items with the name "button" set to var button
    
            //Below is the functionality for all the buttons in the JSP files
            if ((dress == null) || (button == null || "".equals(button))) {
                dress = dao.findFirst();
            } else if ("First".equals(button)) {
                dress = dao.findFirst();
            } else if ("Last".equals(button)) {
                dress = dao.findLast();
                index = dao.size();
            } else if ("Next".equals(button)) {
                dress = dao.findNext(dress);
                if (dress == null) {
                    dress = dao.findFirst();
                }
            } else if ("Prev".equals(button)) {
                dress = dao.findPrevious(dress);
                index = index - 1;
                if (dress == null) {
                    dress = dao.findLast();
                }
            } else if ("Back".equals(button)) {
                target = "/viewDresses.jsp";
            } else if ("List".equals(button)) {
                allDresses = dao.findAll();
                request.setAttribute("dresss", allDresses);
                target = "/dressList.jsp";
            } else if ("Init".equals(button)) {
                factory.init(dao, true);
            } else {
                dress = dao.findFirst();
            }
            dao.close();
    
            session.setAttribute("dress", dress); //Passes the data to the serlvet
            //session.setAttribute("cart", cart); //sets a session for the cart data
    
            ServletContext context = this.getServletContext(); //Returns reference to servlet context
            RequestDispatcher dispatcher = context.getRequestDispatcher(target); //Sets the target (the jsp file) the request & response will be sent to
            dispatcher.forward(request, response); //Forwards the request tot the target above
        }
    
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response); //Points to doGet, so same action will be taken whether loaded by POST or GET
        }
    }
    Last edited by me10lee83; 12-17-2013 at 02:26 AM.


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •