Results 1 to 3 of 3
  1. #1
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Remember state of checked items

    I have a servlet that is basically a shopping cart. You select some items, it totals them up and gives the total of selected items. I want when the back button is clicked, for it to remember what was checked. I have created a map of checked items, but can't figure out how to get it to read if there is data in the getName field. The if statement I'm trying is giving an illegal start of expression error.

    Java Code:
    package homework;
    
    import java.text.DecimalFormat;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    /**
     * @author Tenley
     */
    public class Cart extends HttpServlet {
    
        /**
         * @param request
         * @param response
         * @throws javax.servlet.ServletException
         * @throws java.io.IOException
         */
        
        Item[] items = new Item[7]; //Creating an array for the items class
        Map<String, Item> itemMap = new HashMap<String, Item>(19);
    
        @Override //Filling the items class with the items
        public void init() {
            items[0] = new Item("Alfred Angelo Pleated Strapless Dress", "Who says you can&rsquo;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, false);
            items[1] = new Item("Davids Bridal Sleeveless Chiffon Dress", "A 'must have' for your bridal party. This dress has a high neckline with beaded straps and a keyhole detail. 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, false);
            items[2] = new Item("Jenny Woo 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, false);
            items[3] = new Item("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 a rhinestone flower waistband. It is available in wheat, silver mist, copper, sunset, and guava in sizes 0 to 20W and maternity sizes.", 140.99, false);
            items[4] = new Item("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, false);
            items[5] = new Item("After Six Cocktail Length with Ruched Waist", "Your girls will sweep down the aisle in this sleek gown. Made of soft net with with a grosgrain ribbon sash the one-shoulder dress is availabe in sizes 0 to 30W and all 15 soft net colors.", 139.0, false);
            items[6] = new Item("Dessy Bobbin Net Dress with Rounded Neckline", "Vintage-inspired, the cocktail length dress has an asymmetrically draped bubble skirt. Straps adorned with crystal beading, rhinestones, and sequins make this dress one of a kind. This dress is available in all 50 dream in color shades and sizes 0 to 30W and 8JB to 14JB", 129.99, false);
            for (Item item : items) {
                itemMap.put(item.getName(), item);
            }
        }
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            StringBuilder sb = new StringBuilder(20);
            Map<String, Item> checkedItems = new HashMap<String, Item>(19);
    
            writeStrings(out, top); //Printing the HTML headers
            writeStrings(out, middle); //Start of the table & page title
    
            for (int i = 0; i < items.length; i++) { 
                Item item = items[i];
                sb.append("<tr><td style='border-style:solid; border-width:1px'><label><input type='checkbox' name='buy' value='").append(items[i].getName());
                if (checkedItems.get(item.getName())!=null)) {
                    sb.append("checked");
                }
                sb.append("'/></label></td>");
                sb.append("<td style='border-style:solid; border-width:1px'>").append(item.getName()).append("</td>");
                sb.append("<td style='border-style:solid; border-width:1px'>").append(item.getDescription()).append("</td>");
                sb.append("<td style='border-style:solid; border-width:1px'>$").append(item.getPrice()).append("</td>");
            }
            out.println(sb + "</tr></table>"); 
            writeStrings(out, formEnd); 
            writeStrings(out, bottom); 
        }
    
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException { //This is run when the POST method is called, when the form is submitted
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String[] selected = request.getParameterValues("buy"); //reads in the values of the dress form
            String[] tax = request.getParameterValues("md"); //reads in whether tax is selected
            DecimalFormat df = new DecimalFormat("0.00##"); //When DecimalFormat is called, the number is rounded to two decimal places
    
            double total = 0.0;
            double[] prices = new double[7]; //Creating an array to store the dress prices in
            Map<String, Item> checkedItems = new HashMap<String, Item>(19); //Creating a map to store only checked itesm
            int i = 0;
    
            writeStrings(out, top); //Printing the HTML headers
    
            if (selected != null & !(selected.length == 0)) {
                out.println("<p>You selected:</p>"
                        + "<table style='border-collapse:collapse'><tr><th>Designer</th><th>Price</th></tr>");
                for (String buy : selected) { //Runs each time a "buy" item is checked
                    if (buy != null && !buy.isEmpty()) {
                        Item myItem = itemMap.get(buy);
                        total += myItem.getPrice(); //Adds the value of the item to the total
                        checkedItems.put(myItem.getName(), myItem); //Creates a map of only checked items
                        prices[i] = myItem.getPrice(); //Sends the prices into an array so it can be printed in a table later
                        i++;
                    }
                }
    
                for (i = 0; i < selected.length; i++) {
                    out.println("<tr><td style='border-style:solid; border-width:1px'>" + selected[i]
                            + "</td><td style='border-style:solid; border-width:1px'> $" + df.format(prices[i]) + "</tr>");
                } 
    
                if (tax != null) {
                    out.println("</table>" + "<p>Your sub-total is: $" + total);
                    total *= 1.06;
                    out.println("<br>Your total after 6% tax is $" + df.format(total) + "</p>"
                            + "<form action='Cart' method='GET'>"
                            + "<input type='submit' name='Cart' value='Go back'></form>");
                } else {  
                    out.println("</table>" + "<p>Your total is $" + df.format(total) + "</p>"
                            + "<form action='Cart' method='GET'> "
                            + "<input type='submit' name='Cart' value='Go back'></form>");
                }
                writeStrings(out, bottom);
            } else {
                out.println("Nothing selected");
                out.println("<form action='Cart' method='GET'> \n"
                        + "<input type='submit' name='Cart' value='Go back'></form>");
                writeStrings(out, bottom);
            }
    
        }
    
        private static String[] top = {
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "<title>Dresses</title>",
            "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>",
            "</head>",
            "<body>"
        };
        private static String[] middle = {
            "<h1 style='text-align:center'>Bridesmaid Dresses</h1>",
            "<form action='Cart' method='POST'>",
            "<table style='border-style:solid; border-width:1px; border-collapse:collapse'>"
        };
        private static String[] formEnd = {
            "</table> \n" + "<p><input type='checkbox' name='md' value='md'> Check this box if you are a Maryland resident.</p>\n"
            + "<input type='submit' name='Total' value='Total'>\n"
            + "</form>\n"
            + "<p>When the 'total' button is checked, a shopping cart page is displayed which shows the total cost for all checked items. If the Maryland resident box is checked, 6% tax is added to the total price. The back button on the shopping cart page will return you to this page, and the selected values will still be selected.</p>\n"
            + "<small>Created by Tenley, ID: 0129508</small>"
        };
        private static String[] bottom = {
            "</body>",
            "</html>"
        };
    
        //This allows the code above to be printed out easily
        private void writeStrings(PrintWriter out, String[] esses) {
            for (String s : esses) {
                out.println(s);
            }
            out.flush();
        }
    }
    Last edited by me10lee83; 10-16-2013 at 03:27 PM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,178
    Rep Power
    20

    Default Re: Remember state of checked items

    Back buttons are a pain in the posterior.
    You could try the no-cache route in headers, but I'm not sure that actually works for the back button.
    Other than that I think you're down to using Javascript.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    me10lee83 is offline Member
    Join Date
    Oct 2013
    Posts
    10
    Rep Power
    0

    Default Re: Remember state of checked items

    Looks like the issue was an extra ")" after null. I corrected that and the if statement no longer gave an error, but it wasn't working as intended because the checkedItems map was empty.
    I think I need to save this into the session then return the session data, but not sure what to retrieve exactly, everything I try says it's the wrong type. How can I retrieve the checkedItems session data? (And am I storing it into the array properly?)

    Java Code:
    package homework;
    
    import java.text.DecimalFormat;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * @author Tenley Baldwin
     */
    public class Cart extends HttpServlet {
    
        /**
         * @param request
         * @param response
         * @throws javax.servlet.ServletException
         * @throws java.io.IOException
         */
        public void doDelete(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ; //Requests a URI be removed from the server
        
        public void doHead(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ; //Same as doGet, but without the body, used for getting meta info from headers
        
        public void doOptions(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ; //Gives the supported HTTP methods which can be used to test the functionality of a server
        
        public void doPut(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ; //Used to update or change a resource
        
        public void doTrace(HttpServletRequest request,
                HttpServletResponse response) {
        }
        ; //Received info is sent back so the requester can see if any changes have been made by the servers
    
        Item[] items = new Item[7]; //Creating an array for the items class
        Map<String, Item> itemMap = new HashMap<String, Item>(19); //Creating the map for the items for sale
    
        @Override //Filling the items class with the items
        public void init() {
            items[0] = new Item("Alfred Angelo Pleated Strapless Dress", "Who says you can&rsquo;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, false);
            items[1] = new Item("Davids Bridal Sleeveless Chiffon Dress", "A 'must have' for your bridal party. This dress has a high neckline with beaded straps and a keyhole detail. 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, false);
            items[2] = new Item("Jenny Woo 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, false);
            items[3] = new Item("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 a rhinestone flower waistband. It is available in wheat, silver mist, copper, sunset, and guava in sizes 0 to 20W and maternity sizes.", 140.99, false);
            items[4] = new Item("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, false);
            items[5] = new Item("After Six Cocktail Length with Ruched Waist", "Your girls will sweep down the aisle in this sleek gown. Made of soft net with with a grosgrain ribbon sash the one-shoulder dress is availabe in sizes 0 to 30W and all 15 soft net colors.", 139.0, false);
            items[6] = new Item("Dessy Bobbin Net Dress with Rounded Neckline", "Vintage-inspired, the cocktail length dress has an asymmetrically draped bubble skirt. Straps adorned with crystal beading, rhinestones, and sequins make this dress one of a kind. This dress is available in all 50 dream in color shades and sizes 0 to 30W and 8JB to 14JB", 129.99, false);
            for (Item item : items) { //filling each item in to the itemMap
                itemMap.put(item.getName(), item);
            }
        }
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)//When the servlet is called via GET, either on initial load or via the "back" button this runs
                throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            StringBuilder sb = new StringBuilder(20);
            Map<String, Item> checkedItems = new HashMap<String, Item>(19); //Creating a map for selected items only
            HttpSession session = request.getSession();
    
            writeStrings(out, top); //Printing the HTML headers
            writeStrings(out, middle); //Start of the table & page title
    
            for (int i = 0; i < items.length; i++) { //Creating the table with available items to select
                Item item = items[i];
                sb.append("<tr><td style='border-style:solid; border-width:1px'><label><input type='checkbox' name='buy' value='").append(items[i].getName());
                sb.append("' ");
                if (checkedItems.get(item.getName()) != null) {
                    sb.append("checked");
                } //This wiil set the checkbox if the item in the checkedItems map contains data
                sb.append("/></label></td> \n");
                sb.append("<td style='border-style:solid; border-width:1px'>").append(item.getName());
                sb.append(" ").append(checkedItems.get(item.getName()));
                sb.append("</td>");
                sb.append("<td style='border-style:solid; border-width:1px'>").append(item.getDescription()).append("</td>");
                sb.append("<td style='border-style:solid; border-width:1px'>$").append(item.getPrice()).append("</td> \n");
            }
            out.println(sb + "</tr></table>"); //Printing out the string created in the string builder loop above
            writeStrings(out, formEnd); //End of table/form
            writeStrings(out, bottom); //Page description & HTML close
        }
    
        @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException { //This is run when the POST method is called, when the form is submitted
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String[] selected = request.getParameterValues("buy"); //reads in the values of the dress form
            String[] tax = request.getParameterValues("md"); //reads in whether tax is selected
            DecimalFormat df = new DecimalFormat("##.##"); //When DecimalFormat is called, the number is rounded to two decimal places
            HttpSession session = request.getSession();
    
            double total = 0.0; //The total value of the selected items wil be stored in this variable
            double[] prices = new double[7]; //Creating an array to store the dress prices in
            Map<String, Item> checkedItems = new HashMap<String, Item>(19); //Creating a map to store only checked itesm
            int i = 0;
    
            writeStrings(out, top); //Printing the HTML headers
    
            if (selected != null & !(selected.length == 0)) {
                out.println("<p>You selected:</p>"
                        + "<table style='border-collapse:collapse'><tr><th>Designer</th><th>Price</th></tr>");
                for (String buy : selected) { //Runs each time a "buy" item is checked
                    if (buy != null && !buy.isEmpty()) {
                        Item myItem = itemMap.get(buy);
                        total += myItem.getPrice(); //Adds the value of the item to the total
                        checkedItems.put(myItem.getName(), myItem); //Creates a map of only checked items
                        prices[i] = myItem.getPrice(); //Sends the prices into an array so it can be printed in a table later
                        i++; //Increments the value of i so the next price will be stored in the next spot in the array
                        session.setAttribute(myItem.getName(), checkedItems); //Storing the name and checkItems map into the session
                    }
                }
                
                for (i = 0; i < selected.length; i++) {
                    out.println("<tr><td style='border-style:solid; border-width:1px'>" + selected[i]
                            + "</td><td style='border-style:solid; border-width:1px'> $" + df.format(prices[i]) + "</tr>");
                } //Prints a table of the selected dress names and prices, iterating through the array each time
    
                /*If the MD resident option is checked, the value of tax is multipled by 1.06 for 6% tax,
                 *and the total is printed, rounded to two decimal places below*/
                if (tax != null) {
                    out.println("</table>" + "<p>Your sub-total is: $" + total);
                    total *= 1.06;
                    out.println("<br>Your total after 6% tax is $" + df.format(total) + "</p>"
                            + "<form action='Cart' method='GET'>"
                            + "<input type='submit' name='Cart' value='Go back'></form>");
                } else {//These above and below create a "back" button which loads this servlet via GET, difference tax or not
                    out.println("</table>" + "<p>Your total is $" + df.format(total) + "</p>"
                            + "<form action='Cart' method='GET'> "
                            + "<input type='submit' name='Cart' value='Go back'></form>");
                    //Outputs the total value, rounded to two decimal places if tax is not selected
                }
                writeStrings(out, bottom);
            } else { //If no items are checked on the form before hitting total
                out.println("Nothing selected");
                out.println("<form action='Cart' method='GET'> \n"
                        + "<input type='submit' name='Cart' value='Go back'></form>");
                writeStrings(out, bottom);
            }
    
        }
    //Below is the HTML code sections to be used with writeStrings
        private static String[] top = {
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "<title>Dresses</title>",
            "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>",
            "</head>",
            "<body>"
        };
        private static String[] middle = {
            "<h1 style='text-align:center'>Bridesmaid Dresses</h1>",
            "<form action='Cart' method='POST'>",
            "<table style='border-style:solid; border-width:1px; border-collapse:collapse'>"
        };
        private static String[] formEnd = {
            "</table> \n" + "<p><input type='checkbox' name='md' value='md'> Check this box if you are a Maryland resident.</p>\n"
            + "<input type='submit' name='Total' value='Total'>\n"
            + "</form>\n"
            + "<p>When the 'total' button is checked, a shopping cart page is displayed which shows the total cost for all checked items. If the Maryland resident box is checked, 6&#37; tax is added to the total price. The back button on the shopping cart page will return you to this page, and the selected values will still be selected.</p>\n"
            + "<small>Created by Tenley Baldwin, ID: 0129508</small>"
        };
        private static String[] bottom = {
            "</body>",
            "</html>"
        };
    
        //This allows the code sections above to be printed out easily
        private void writeStrings(PrintWriter out, String[] esses) {
            for (String s : esses) {
                out.println(s);
            }
            out.flush();
        }
    }

Similar Threads

  1. Replies: 7
    Last Post: 08-23-2013, 12:25 PM
  2. Replies: 8
    Last Post: 12-10-2011, 05:54 PM
  3. why we need checked exceptions
    By akiravelmont in forum New To Java
    Replies: 2
    Last Post: 12-03-2011, 08:51 PM
  4. Replies: 2
    Last Post: 02-14-2011, 03:27 PM

Posting Permissions

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