Javaweb 实验7 JSP内置对象II实现购物车

我发现了有些人喜欢静静看博客不聊天呐,

但是ta会点赞。

这样的人呢帅气低调有内涵,

美丽大方很优雅。

说的就是你,

不用再怀疑哦

实验七 JSP内置对象II

目的:

  1. 掌握JSP内置对象的使用。
  2. 理解JSP的作用域
  3. 掌握session,application对象的使用

实验要求:

  1. 完成实验题目
  2. 要求提交实验报告,将代码和实验结果页面截图放入报告中

实验过程:

一、结合之前所学的相关技术,编写代码实现以下购物车功能:

  1. 编写一个页面,展现商品列表(静态页面),页面右上方有登陆、结账和查看购物车三个按钮,下方展示网站历史访问的人数
  2. 用户点击商品后,可以将商品加入购物车
  3. 用户点击登陆,跳转到登陆页面
  4. 用户点击结账,若已登陆跳转至结账页面,否则跳转到登陆页面登陆后再跳转到结账页。
  5. 用户点击查看购物车按钮,跳转至购物车页面,可查看购物车列表、增加商品数量或者删除商品

【参考代码】

登录页面Login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
</head>
<body>
<h2>登录</h2>
<form onsubmit="handleLogin(event)">
    <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" required>
    </div>
    <div>
        <label for="password">密码:</label>
        <input type="password" id="password" required>
    </div>
    <button type="submit">登录</button>
</form>

<script>
    function handleLogin(event) {
        event.preventDefault();
        let username = document.getElementById("username").value;
        let password = document.getElementById("password").value;

        // 假设简单验证用户
        if (username === "111" && password === "111") {
            localStorage.setItem('loggedIn', true);
            alert('登录成功!');
            window.location.href = 'index.html';
        } else {
            alert('用户名或密码错误!');
        }
    }
</script>
</body>
</html>

商品页面index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品列表</title>
    <style>
        /* 页面样式 */
        body {
            font-family: Arial, sans-serif;
        }
        nav {
            display: flex;
            justify-content: flex-end;
            padding: 10px;
            background-color: #f8f8f8;
        }
        nav button {
            margin-left: 10px;
        }
        .products {
            display: flex;
            gap: 20px;
            padding: 20px;
        }
        .product {
            border: 1px solid #ccc;
            padding: 10px;
            text-align: center;
        }
        footer {
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>
<nav>
    <button onclick="navigateTo('login')">登录</button>
    <button onclick="navigateTo('checkout')">结账</button>
    <button onclick="navigateTo('cart')">查看购物车</button>
</nav>

<div class="products">
    <div class="product" onclick="addToCart('商品1')">
        <h3>商品1 10元</h3>
        <p>点击添加到购物车</p>
    </div>
    <div class="product" onclick="addToCart('商品2')">
        <h3>商品2 20元</h3>
        <p>点击添加到购物车</p>
    </div>
    <div class="product" onclick="addToCart('商品3')">
        <h3>商品3 30元</h3>
        <p>点击添加到购物车</p>
    </div>
</div>

<footer>
    本网站历史访问人数:123</span>
</footer>

<script>

    function navigateTo(page) {
        if (page === 'login') {
            window.location.href = 'login.html';
        } else if (page === 'checkout') {
            if (localStorage.getItem('loggedIn')) {
                window.location.href = 'checkout.html';
            } else {
                window.location.href = 'login.html';
            }
        } else if (page === 'cart') {
            window.location.href = 'cart.html';
        }
    }

    function addToCart(product) {
        let price;
        if (product === '商品1') {
            price = 10;
        } else if (product === '商品2') {
            price = 20;
        } else if (product === '商品3') {
            price = 30; // 新商品
        }

        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        let item = cart.find(p => p.name === product);

        if (item) {
            item.quantity += 1;
        } else {
            cart.push({ name: product, quantity: 1, price: price }); // 存储价格
        }

        localStorage.setItem('cart', JSON.stringify(cart));
        alert(product + ' 已添加到购物车!');
    }
</script>
</body>
</html>

购物车页面cart.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
</head>
<body>
<h2>购物车内容</h2>
<ul id="cartItems">
    <!-- 购物车商品列表 -->
</ul>
<button onclick="checkout()">结账</button>

<script>
    function loadCart() {
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        const cartItems = document.getElementById('cartItems');
        cartItems.innerHTML = '';

if (cart.length === 0) {
        cartItems.innerHTML = '<li>购物车为空</li>';
        return;
}

        cart.forEach((item, index) => {
            const li = document.createElement('li');
            li.textContent = `${item.name} - 单价: ${item.price}元, 数量: ${item.quantity}`;
            const increaseBtn = document.createElement('button');
            increaseBtn.textContent = '+';
            increaseBtn.onclick = () => changeQuantity(index, 1);
            const decreaseBtn = document.createElement('button');
            decreaseBtn.textContent = '-';
            decreaseBtn.onclick = () => changeQuantity(index, -1);
            const removeBtn = document.createElement('button');
            removeBtn.textContent = '删除';
            removeBtn.onclick = () => removeItem(index);

            li.appendChild(increaseBtn);
            li.appendChild(decreaseBtn);
            li.appendChild(removeBtn);
            cartItems.appendChild(li);
        });
    }

    function changeQuantity(index, amount) {
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        cart[index].quantity += amount;
        if (cart[index].quantity <= 0) {
            cart.splice(index, 1);
        }
        localStorage.setItem('cart', JSON.stringify(cart));
        loadCart();
    }

    function removeItem(index) {
        let cart = JSON.parse(localStorage.getItem('cart')) || [];
        cart.splice(index, 1);
        localStorage.setItem('cart', JSON.stringify(cart));
        loadCart();
    }

    function checkout() {
        if (localStorage.getItem('loggedIn')) {
            alert('正在跳转至结账页面...');
            window.location.href = 'checkout.html';
        } else {
            alert('请先登录');
            window.location.href = 'login.html';
        }
    }

    //初始化购物车内容
    loadCart();
</script>
</body>
</html>

结账页面Checkout.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>结账</title>
    <script>
        function checkLoginStatus() {
            if (!localStorage.getItem('loggedIn')) {
                // 如果未登录,跳转到登录页面
                window.location.href = 'login.html';
            }
        }

        function loadCart() {
            let cart = JSON.parse(localStorage.getItem('cart')) || [];
            const cartItems = document.getElementById('cartItems');
            cartItems.innerHTML = '';
            let total = 0; // 用于计算总价

            if (cart.length === 0) {
                cartItems.innerHTML = '<li>购物车为空</li>';
                return;
            }

            cart.forEach(item => {
                const li = document.createElement('li');
                li.textContent = `${item.name} - 单价: ${item.price}元, 数量: ${item.quantity}`;
                cartItems.appendChild(li);
                total += item.price * item.quantity; // 累加总价
            });

            // 显示总价
            const totalLi = document.createElement('li');
            totalLi.textContent = `总价: ${total}元`;
            cartItems.appendChild(totalLi);
        }

        function completeCheckout() {
            alert('结账成功!感谢您的购买。');
            // 清空购物车
            localStorage.removeItem('cart');
            window.location.href = 'index.html'; // 返回到商品列表页面
        }

        function goBack() {
            window.location.href = 'cart.html';
        }

        // 页面加载时检查登录状态
        window.onload = function() {
            checkLoginStatus();
            loadCart();
        }
    </script>
</head>
<body>
<h2>结账</h2>
<h3>购物车内容</h3>
<ul id="cartItems">
    <!-- 购物车商品列表 -->
</ul>
<button onclick="completeCheckout()">完成结账</button>
<button onclick="goBack()">返回购物车</button>
</body>
</html>

【运行结果】

点击“查看购物车”

点击“完成结账”,清空购物车

商品未添加到购物车:

二、实验心得。

使用了其他的技术来实现的购物车功能,写法类似,只是使用的对象不同

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值