Javaweb 实验8 JSP访问数据库(一)

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

但是ta会点赞。

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

美丽大方很优雅。

说的就是你,

不用再怀疑哦

Javaweb 实验7 JSP内置对象II实现购物车_实验7 jsp内置对象(二)-CSDN博客

本次实验是延续上次实验的购物车网页,只不过商品信息改成了从数据库读取

一、JSP访问数据库的步骤:

①加载数据库驱动程序;②建立连接对象;③创建语句对象;④获得结果集;⑤关闭有关连接对象。

二、实现书籍信息的查询和展示

1、新增数据库DBStore,新增一张表book,包含书籍编号、书籍名称、书籍描述、书籍价格等字段(供参考,可以按需要增加其他字段),并为book表添加一些记录。

字段

类型

备注

id

int

记录id

bookNo

Varchar(32)

书籍编号

bookName

Varchar(32)

书名

bookDescription

varchar(128)

书籍描述

cost

decimal

价格

2、结合实验7的购物车实验,编写书籍的查询逻辑,使得书籍展示页面的内容可以根据数据库中已有的书籍信息进行展示。

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.sql.*" %>
<%
    String url = "jdbc:mysql://localhost:3306/dbstore";
    String username = "root";
    String password = "";
    Connection conn = null;

    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection(url, username, password);

    PreparedStatement pst = null;
    pst = conn.prepareStatement("SELECT * FROM book");
    ResultSet rs = null;//执行查询
    rs = pst.executeQuery();
%>

<html>
<head>
    <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;
            flex-wrap: wrap;
            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>

<%
    if (rs != null) {
        while(true){
            try {
                if (!rs.next()) break;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            int id = rs.getInt("id");
            String bookNo = rs.getString("bookNo");
            String bookName = rs.getString("bookName");
            String bookDescription = rs.getString("bookDescription");
            //获取cost,类型decimal
            double cost = rs.getDouble("cost");
%>
<div class="product" id="product">
    <h3><%=bookName%> <%=cost%>元</h3>
    <p><%=bookDescription%></p>
    <p>书籍编号: <%=bookNo%></p>
    <label>
        <input style="text-align: center" onclick="addToCart('<%=bookName%>', <%=cost%>)" value="添加到购物车" >
    </label>
</div>
<%
        }
    }
%>

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

<script>
    async function loadBooks() {
        try {
            const response = await fetch('book');
            console.log(response); // 打印响应
            const books = await response.json();
            console.log(books); // 打印响应

            const productsDiv = document.getElementById('products');
            productsDiv.innerHTML = ''; // 清空现有内容

            books.forEach(book => {
                const productDiv = document.createElement('div');
                productDiv.classList.add('product');
                productDiv.onclick = () => addToCart(book.bookName, book.cost);
                productDiv.innerHTML = `
                    <h3>${book.bookName} ${book.cost}元</h3>
                    <p>${book.bookDescription}</p>
                    <p>书籍编号: ${book.bookNo}</p>
                `;
                productsDiv.appendChild(productDiv);
            });
        } catch (err) {
            console.error('Error fetching books:', err);
        }
    }

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

    function addToCart(product, price) {
        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 + ' 已添加到购物车!');
    }

    // 初始化加载书籍
    window.onload = loadBooks;
</script>
</body>
</html>

运行结果:

点击“查看购物车”

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

商品未添加到购物车: