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 12 of 12
  1. #1
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Null Pointer Exception

    This is my first attempt at Java. I have a servlet that is basically a shopping cart, you select some items on a website then it is supposed to display the name and price of the checked items and a total price. However when I press total, I get a null pointer exception error. It points to line 95 in cart.java, but I'm not sure what the issue is.

    Below are the code for the different files associated with this.

    Cart.java
    Code:
    package homework;
    
    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];
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect("tb08hw1.html");
        } /*When the browser requests this page via the GET method, it will redirect the browser to the html page,
         * so it will always redirect to the html page unless called by another method like post (see below) */
    
    
        public void doDelete(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Requests a URI be remoted from the server
        public void doHead(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Same as get, 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
        
        private static Map<Double, String> DRESSES = new HashMap<Double, String>();
    
        {
            DRESSES.put(149.99, "Alfred Angelo");
            DRESSES.put(149.00, "David&rsquo;s Bridal");
            DRESSES.put(159.99, "Jenny Woo");
            DRESSES.put(140.99, "Lela Rose");
            DRESSES.put(189.99, "Donna Morgan");
            DRESSES.put(139.00, "After Six");
            DRESSES.put(129.99, "Dessy");
        } // Initializing static elements, associates the label names with their values
    
        ; 
     //The doPost method below is called when the total button is selected on the website
     @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            String[] selected = request.getParameterValues("buy");
            StringBuilder sb = new StringBuilder(20);
            writeStrings(out, top);
            double[] totalArray = new double[7];
            //If no items are checked on the html file before hitting total:
            if (selected == null || selected.length == 0) {
                out.println(sb);
                out.println("Nothing checked");
                out.println("<p><a href=\"tb08hw1.html\">Go back and make a selection</a></p>");
                writeStrings(out, bottom);
            } else {
                out.println("<p>You selected</p>");
                for (int i = 0; i < items.length; i++) { //For loops runs once per item
                    if (items[i].isSelected() == true) { 
    //If an item is selected, this will output the name & price, and put the price into a new array
                        Item item = items[i];
                        sb.append("<table><tr><td>").append(item.getName()).append("</td>");
                        sb.append("<td>").append(item.getPrice()).append("</td></tr></table>");
                        totalArray[i] = item.getPrice();
                    } else {
                        continue;
                    }
                }
                double total = 0.0;
                for (int i = 0; i < totalArray.length; i++) {
                    total += totalArray[i] ;
                } //The price of all selected items was input in this array above. Added together to get the total here
                out.println("Your total is" + total);
                out.println("<p><a href=\"tb08hw1.html\">Go back and change your selection</a></p>");
            }
    
            writeStrings(out, bottom);
        }
    //Below is the HTML code that will be displayed when total is selected
        private static String[] top = {
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "<title>Checkout</title>",
            "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">",
            "</head>",
            "<body>",
            "<table>"};
        private static String[] bottom = {
            "</table",
            "</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);
            }
        }
    }
    Item.java
    Code:
    public class Item {
    
        private String name;
        private String description;
        private double price = 0.0;
        private boolean selected = false;
    
        public Item() {
        }
    
        public Item(String aName, String aDesc, double aPrice, Boolean isSelected) {
            name = aName;
            description = aDesc;
            price = aPrice;
            selected = isSelected;
        }
    
        /**
         * @return the name
         */
        public String getName() {
            return name;
        }
    
        /**
         * @param name the name to set
         */
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * @return the description
         */
        public String getDescription() {
            return description;
        }
    
        /**
         * @param description the description to set
         */
        public void setDescription(String description) {
            this.description = description;
        }
    
        /**
         * @return the price
         */
        public double getPrice() {
            return price;
        }
    
        /**
         * @param price the price to set
         */
        public void setPrice(double price) {
            this.price = price;
        }
    
        /**
         * @return the selected
         */
        public boolean isSelected() {
            return selected;
        }
    
        /**
         * @param selected the selected to set
         */
        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }
    HTML file
    Code:
    <!DOCTYPE html>
    
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>AIT 618 Homework 1</title>
    </head>
    
    <body>
        <h1 style="text-align:center">Bridesmaid Dresses</h1>
    
        <form action="tb08hw1" method="POST"> 
            <table style="border-style:solid; border-width:1px; border-collapse:collapse">
                <tr>
                    <th></th>
                    <th>Name</th>
                    <th>Description</th>
                    <th>Price</th>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="buy" value=149.99/></td>
                    <td style="border-style:solid; border-width:1px">Alfred Angelo</label> Pleated Strapless Dress</td>
                    <td style="border-style:solid; border-width:1px">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.</td>
                    <td style="border-style:solid; border-width:1px">$149.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="buy" value=149.00/></td>
                    <td style="border-style:solid; border-width:1px">David&rsquo;s Bridal</label> Sleeveless Chiffon Dress</td>
                    <td style="border-style:solid; border-width:1px">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.</td>
                    <td style="border-style:solid; border-width:1px">$149.00</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="buy" value=159.99/></td>
                    <td style="border-style:solid; border-width:1px">Jenny Woo</label> Organza Strapless Dress</td>
                    <td style="border-style:solid; border-width:1px">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.</td>
                    <td style="border-style:solid; border-width:1px">$159.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="buy" value=140.99/></td>
                    <td style="border-style:solid; border-width:1px">Lela Rose</label> Chiffon Strappless Dress with Cap Sleeves</td>
                    <td style="border-style:solid; border-width:1px">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.</td>
                    <td style="border-style:solid; border-width:1px">$140.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="buy" value=189.99/></td>
                    <td style="border-style:solid; border-width:1px">Donna Morgan</label> Strapless Satin Ballgown</td>
                    <td style="border-style:solid; border-width:1px">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.</td>
                    <td style="border-style:solid; border-width:1px">$188.99</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="buy" value=139.00/></td>
                    <td style="border-style:solid; border-width:1px">After Six</label> Cocktail Length with Ruched Waist</td>
                    <td style="border-style:solid; border-width:1px">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.</td>
                    <td style="border-style:solid; border-width:1px">$139.00</td>
                </tr>
                <tr>
                    <td style="border-style:solid; border-width:1px"><label><input type="checkbox" name="buy" value=129.99/></td>
                    <td style="border-style:solid; border-width:1px">Dessy</label> Bobbin Net Dress with Rounded Neckline</td>
                    <td style="border-style:solid; border-width:1px">Vintage-inspired, the cocktail length dress has an asymetrically 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</td>
                    <td style="border-style:solid; border-width:1px">$129.99</td>
                </tr>
            </table>
            <p><input type="checkbox" name="md" value=.06> Check this box if you are a Maryland resident.</p>
            <input type="submit" name="Total" value="Total">
        </form>
    
        <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>
    </body>
    </html>
    Last edited by me10lee83; 10-11-2013 at 01:22 AM.

  • #2
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Sorry about the HTML, didn't realize that wasn't a supported tag on here

  • #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    You should be able to edit them and change them to the [code][/code] tags instead.
    Can you post the stack trace for the null pointer exception please? I don't do servlet or JSP work, but if its a null pointer I can probably help you find that.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #4
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I was going to go back and edit the HTML tags to CODE tags, but don't see the option to edit.
    Anyway, is this what you wanted?

    java.lang.NullPointerException
    homework.Cart.doPost(Cart.java:95)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)

    EDIT: Ok, now I'm seeing edit! On a different computer now, maybe Chrome doesn't support edit mode and Firefox does...
    Last edited by me10lee83; 10-11-2013 at 12:38 AM.

  • #5
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    After looking at it more I found the problem... but not sure how to fix it. I'd created the array, but haven't created the objects in the array. The map wasn't being used at all.

    I've corrected that now (new code below), and no longer get a NullPointerException, however it's not working properly. It does not output the name and price of the selected items, and it's not adding the values.

    Part of the issue I think is line 101 "String dress = DRESSES.get(buy);" Netbeans is giving a warning, "Given object cannot contain instances of String (expected Double)" and line 82 "String[] selected = request.getParameterValues("buy");". How do I request the double values? Also, the map data is not being added to the Items array I don't think which is prob at least part of the issue as well. How do I accomplish this, or just iterate through the array and not use the Items.class if that would be easier.

    Code:
    package homework;
    
    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 Baldwin
     */
    public class Cart extends HttpServlet {
    
        /**
         * @param request
         * @param response
         * @throws javax.servlet.ServletException
         * @throws java.io.IOException
         */
        Item[] items = new Item[7];
    
        @Override
        public void doGet(HttpServletRequest request,
                HttpServletResponse response)
                throws ServletException, IOException {
            response.sendRedirect("tb08hw1.html");
        } /*When the browser requests this page via the GET method, it will redirect the browser to the html page,
         * so it will always redirect to the html page unless called by another method like post (see below) */
    
    
        public void doDelete(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Requests a URI be remoted from the server
        public void doHead(HttpServletRequest request,
                HttpServletResponse response) {
        }
    
        ;
        //Same as get, 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
        
        private static Map<Double, String> DRESSES = new HashMap<Double, String>();
    
        {
            DRESSES.put(149.99, "Alfred Angelo");
            DRESSES.put(149.00, "David&rsquo;s Bridal");
            DRESSES.put(159.99, "Jenny Woo");
            DRESSES.put(140.99, "Lela Rose");
            DRESSES.put(189.99, "Donna Morgan");
            DRESSES.put(139.00, "After Six");
            DRESSES.put(129.99, "Dessy");
        } // Initializing static elements, associates the label names with their values
    
        ; 
     //The doPost method below is called when the total button is selected on the website
     @Override
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            String[] selected = request.getParameterValues("buy");
            StringBuilder sb = new StringBuilder(20);
            writeStrings(out, top);
            double[] totalArray = new double[7];
            
            //If no items are checked on the html file before hitting total:
            if (selected == null || selected.length == 0) {
                out.println(sb);
                out.println("Nothing selected");
                out.println("<p><a href=\"tb08hw1.html\">Go back and make a selection</a></p>");
                writeStrings(out, bottom);
            } else {
                out.println("<p>You selected</p>");
                out.println("<table>");
                for (String buy : selected) {
                    //for (int i = 0; i < items.length; i++) { //For loops runs once per item
                    if (buy == null || buy.isEmpty()) {
                        continue;
                    }
                    String dress = DRESSES.get(buy);
                    int i = 0;
                    if (dress != null && !dress.isEmpty()) {
                        //if (items[i].isSelected() == true) { 
                        Item item = items[i];
                        sb.append("<tr><td>").append(item.getName()).append("</td>");
                        sb.append("<td>").append(item.getPrice()).append("</td></tr>");
                        totalArray[i] = item.getPrice();
                    } else {
                        continue;
                    }
                }
                double total = 0.0;
                for (int i = 0; i < totalArray.length; i++) {
                    total += totalArray[i];
                } //The price of all selected items was input in this array above. Added together to get the total here
                out.println("</table>");
                out.println("Your total is $" + total);
                out.println("<p><a href=\"tb08hw1.html\">Go back and change your selection</a></p>");
            }
    
            writeStrings(out, bottom);
        }
    //Below is the HTML code that will be displayed when total is selected
        private static String[] top = {
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "<title>Checkout</title>",
            "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">",
            "</head>",
            "<body>",
            "<table>"};
        private static String[] bottom = {
            "</table",
            "</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);
            }
        }
    }
    Last edited by me10lee83; 10-11-2013 at 01:49 PM.

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Gotcha, the dataset is best checked simply before you intend to read from it. If you have already initialized it to the proper size, than there is no chance a *write* can fail (assuming datatype is correct of course, unless something is *really* broken, like beyond code issue broken ), so the problem is a read.
    The easiest thing to do is simply use a try/catch for a NullPointerException. Alternatively, ensure you capture an object from an array and check its null status before you operate on it. IE:
    PHP Code:
    String[] astr = new String[4];
    String str astr[2];
    if (
    str != null)
    {
        
    System.out.println(str.toUpperCase());

    For example. Try catch is pretty much the same:
    PHP Code:
    try
    {
        
    System.out.println(str.toUpperCase());
    }
    catch (
    NullPointerException ex)
    {

    They both have about the same logic.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #7
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I just edited my previous post about finding the mistake. I submitted the post too soon, and didn't realize you'd responded until I ended it.
    I've fixed the original issue, but have a new one now. Thanks!

  • #8
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    I can't really tell you what to do with the servlet request, but that may not be your problem:
    PHP Code:
        private static Map<DoubleStringDRESSES = new HashMap<DoubleString>();

        {
            
    DRESSES.put(149.99"Alfred Angelo");
            
    DRESSES.put(149.00"David&rsquo;s Bridal");
            
    DRESSES.put(159.99"Jenny Woo");
            
    DRESSES.put(140.99"Lela Rose");
            
    DRESSES.put(189.99"Donna Morgan");
            
    DRESSES.put(139.00"After Six");
            
    DRESSES.put(129.99"Dessy");
        } 
    // Initializing static elements, associates the label names with their values 
    DRESSES hashtable will be indexing using the key 129.99 to value Dessy for example. Given the error you see with it expecting a double and getting a string, that would suggest you are providing it with "Dessy", and wanting the number 129.99 returned. If you want to give it the name and get the number, than swap what you have in the put command; key, value is the order. If it is by number to get the name (which means you could run into conflict since you can only have one key of a given value), you need to cast the input to a Double before requesting the get from the hashtable. The Double class has a static .parseDouble on it, so you can give it a string and have it return a Double.

    As for Item, I don't see an Item class, but nothing here indicates how you convert a String into an Item.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #9
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you, I realized that I had the name and values swapped in the map. Once I corrected that I was able to get the rest of it working as desired, without using the item class (for now).
    I would like to be able to click the "go back" link and have the items that were checked, still checked. What is the easiest way to do this, a session?

  • #10
    New Coder
    Join Date
    May 2013
    Posts
    17
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I've created a separate map for checked items only and have the doGet set to add "checked" to the item if the item name in checkedItems is not null. I just need to save the checkedItems data when doGet is called again by the "back" button
    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?)

    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% 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();
        }
    }

  • #11
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Yeah, if you need to retain a persistence than a session would be the way to go. I can't help you with that though since I don't do the servlet or JSP stuff, so in java world I'm not used to not being able to persist.
    If this were in PHP it'd be easy to deal with sessions .
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • #12
    New to the CF scene
    Join Date
    Dec 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    you should check return variale is not null before use.


  •  

    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
    •