Servlet-Based Shopping Cart Solution

I recently made changes to a simple shopping cart code that originally added products from a drop-down list of games on an html page. I decided to modify the HTML by removing the drop down list and instead adding an 'add to cart' button for each game. However, I am facing difficulties in editing the cart to add the games whenever any 'add to cart' button is clicked. It's worth noting that my server-side code is utilizing jetty-9 servlets.

I would greatly appreciate some guidance and assistance!

Below is the original cart code that functioned with the drop-down list:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Cart extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
        String s, goods[] = {"Fifa 15", "Battlefield 5", "GTA 6"};
        double price []={10,20,30};
        double cost;
        PrintWriter out = res.getWriter();
        res.setContentType("text/html");
        HttpSession session = req.getSession(true);

        if ( session == null ) return;
        for (int i = 0; i < goods.length; i++)
        if ( session.getAttribute(goods[i]) == null )
            session.setAttribute(goods[i], new Integer(0));

        if ( (s = req.getParameter("buy")) != null ) {
            int n = ((Integer)session.getAttribute(s)).intValue();
            session.setAttribute(s, new Integer(n + 1));
        }
        out.println("<html><body><h2>Shopping Cart</h2><ul>");
        for (int i = 0; i < goods.length; i++) {
            int n = ((Integer)session.getAttribute(goods[i])).intValue();
            if ( n > 0 ){
                out.println("<li><b>" + goods[i] + "</b> : " + n +":"+ price[i] +"</li>");
                cost=n*price[i];
                out.println(cost);}
            }
        out.println("</ul></body></html>");
    }
}

Additionally, here is the updated HTML page displaying the games:

<html>
Games
<head>
</head>
<body>
    <form  action="http://localhost:8080/apps/Cart"method="post" >

        Fifa 15 </br> 
        <img src="images/fifa-15.jpg" width = 200 height = 300 alt="image" /></br>
        <input type="submit" value="add to cart" ></br> 

        Battlefield 4</br>
        <img src="images/battlefield-4.jpg" width = 200 height = 300 alt="image" /></br>
        <input type="submit" value="add to cart" name ="battle"></br>

        GTA 5</br>
        <img src="images/gta-5.jpg" width = 200 height = 300 alt="image" /></br>
        <input type="submit" value="add to cart" name = "gta">
    </form>
</body>
</html>

Answer №1

Make sure to update your code as follows:

HttpSession session = req.getSession(true);

    for (int i = 0; i < goods.length; i++) {
        if (session.getAttribute(goods[i]) == null)
            session.setAttribute(goods[i], new Integer(0));
    }

    if ((s = req.getParameter("fifa")) != null) {
        int n = ((Integer) session.getAttribute(goods[0])).intValue();
        session.setAttribute(goods[0], new Integer(n + 1));
    } else if ((s = req.getParameter("battle")) != null) {
        int n = ((Integer) session.getAttribute(goods[1])).intValue();
        session.setAttribute(goods[1], new Integer(n + 1));
    } else if ((s = req.getParameter("gta")) != null) {
        int n = ((Integer) session.getAttribute(goods[2])).intValue();
        session.setAttribute(goods[2], new Integer(n + 1));
    }

Here's the corresponding HTML content:

    Fifa 15 </br> 
    <img src="images/fifa-15.jpg" width = 200 height = 300 alt="image" /></br>
    <input type="submit" value="add to cart" name = "fifa"></br> 

    Battlefield 4</br>
    <img src="images/battlefield-4.jpg" width = 200 height = 300 alt="image" /></br>
    <input type="submit" value="add to cart" name ="battle"></br>

    GTA 5</br>
    <img src="images/gta-5.jpg" width = 200 height = 300 alt="image" /></br>
    <input type="submit" value="add to cart" name = "gta">

Based on the button pressed, customize the actions accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Suggestions for relocating this function call from my HTML code

I have been working on updating a javascript function that currently uses an inline event handler to a more modern approach. My goal is to eliminate the unattractive event handler from the actual HTML code and instead place it in a separate modular javascr ...

In what ways can two identical-looking arrays actually be distinct from each other?

Explore this JavaScript snippet: var st, ary, ary1, ary2; ary = [["a","b","c"], ["d","e","f"]]; // 2D array ary1 = ary[1]; st = "d,e,f"; ary2 = st.split(','); st = typeof(ary1) + " " + ary1.length + " " + ary1 + '\n'; // A ...

Adding new information to an associative or multidimensional array

In my web application, there is a functionality that involves selecting a Country which then populates the City select dropdown. Once a city is selected, a radius is added surrounding that particular city. var countrySet = new Array; var citySet = new Arr ...

Simplified jQuery function for multiple div mouseover operations

Uncertain about the accuracy of my title. Due to certain reasons, I need to assign different IDs for the class, as it only detects ID and not class when hovered over. Therefore, I have created a CSS version where the opacity of a specific div will change t ...

Create an electron application in "development" mode and assemble it for distribution

My application is an Electron app developed with Vue.js, and I am looking to create both a production build and a development build. My goal is to utilize the NODE_ENV environment variable to adjust the behavior of the application once it is packaged. Th ...

How can you toggle the visibility of the grid in Three.js using GridHelper?

I have successfully added a plane and grid to my 3D scene using Gridhelper: // PLANE XY static var gridplaneSize = 20; var color = 0xFFDCBB; var plGeometry = new THREE.PlaneGeometry(gridplaneSize, gridplaneSize); var plMaterial = new THREE.MeshBasicMateri ...

Ways to validate the existence of URLs from different domains with javascript

I'm attempting to verify the existence of a URL from another domain on my own domain ('https://radiusofficefurniture.ie') using JavaScript like this: var request = new XMLHttpRequest(); request.open('GET', 'https://www.mozil ...

How to locate a dynamically changing element by its ID using Selenium and Java

Having an xPath like this: //*[@id="searchpopupSCH_USER_1496689382343"] However, the 13 digits at the end represent a timestamp that changes every time you re-test or click. For instance, On the first tab, //*[@id="searchpopupSCH_USER_1496689382343"] On ...

The button seems to be invisible within the app even after it has been successfully installed

I attempted to create a QR Code scanner, but when I installed the apk, the button did not appear in the correct location. Below is the code for the button: <Button android:id="@+id/scan_btn" android:layout_width="127dp" android:layout_hei ...

Organizing controllers in separate files within AngularJS

I've been working on modularizing an AngularJS project by implementing different controllers in their own JS files. However, I'm facing issues with getting them to work properly. Below is my config.js file where the primary module is defined: ( ...

Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this: { "id":2026 "url": "https:// ... " , "large_url":null, "source_id":609, "copyright":"CC0", "site":"unsplash" } ...

Grabbing information from a database and showcasing it using basic JSON in Java

Could you please advise on how to generate the desired JSON output shown below? { "Result":"OK", "Records":[ {"PersonId":1,"Name":"Benjamin Button","Age":17,"RecordDate":"\/Date(1320259705710)\/"}, {"PersonId":2,"Name":"Douglas Adams","Age ...

Attempting to access session variable set prior to the request in Django view tests proves to be inaccessible

To store a specific state between HTTP requests, I opted to use session variables stored in cookies as I do not utilize the JS frontend. My session settings are configured as follows: SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESS ...

Vue Js does not include images in the dist directory when the build process is completed

In my VueJs 3 project, I am working with a list of PNG images stored in the src/assets/pngs/ directory. Within my Vue component, I use a For loop to dynamically create the list by setting the image name as the source for the img tag. This implementation wo ...

Is it possible to determine if a JavaScript/jQuery effect or plugin will function on iPhone and iPad without actually owning those devices?

Is there a way to ensure that a javascript/jquery effect or plugin that works well on all desktop browsers will also work on iPhone and iPad without actually owning those devices? Can I rely on testing it on the latest Safari for Windows to guarantee comp ...

Insert a gap between JFrame and JPanel in your code

What is the best way to create space between a JFrame and a JPanel placed inside it? I want to make sure that the components inside the JPanel are not too close to the edges of the JFrame. ...

Issues with Retrieving Data from Microsoft Dynamics 365 CRM

As of late, I've been given the task of automating MS CRM 365 using Selenium Automation. I've decided to utilize Gradle and Java for this project within IntelliJ. However, a major hurdle I'm facing is the inability to access elements on a f ...

Sometimes, the `undefined` TypeError can unexpectedly pop up while making Ajax calls

Here is my issue with AJAX request and response: I have around 85 HTML pages that all use the same AJAX request. However, when working with these files, I sometimes encounter the following error. AJAX $(document).ready(function(){ localStorage.setIte ...

Is it possible to utilize onclick for various table cells in jQuery?

I have a situation where I need to loop through dates and display table content accordingly. Could someone please assist me in figuring out how to do this? index.html.erb <% @batches.each do |batch| %> <tr> **<td class = "pie" id ...

Angular 2 Error: Unable to access the property 'value' as it is undefined

Whenever I click on the Submit button, this error pops up in the browser console. https://i.sstatic.net/57a5N.jpg In my application, I am attempting to retrieve information about the code uploaded by a Student. I am at a loss as to why this error is bein ...