球助 球助 !!
问题描述:数据库中有张books表,存放了书籍的相关信息,如ISBN编号、书名、作者、价格和库存数量等信息。当我们新进了同样的书时,希望能更改库存数量。同时,如果有折扣,我们同样希望可以更改书的价格。
要求:
使用MVC模式(JSP+Servlet+JavaBean)
使用MySQL数据库创建相应的表
使用JDBC连接数据库
不用做出一模一样的窗口界面,功能实现在网页中体现就可以!
问题分析:
1.使用三层结构来完成数据库操作,使用业务类来完成数据库books表的字段的更新操作。
2.需要建立一个Servlet,用来以表格的形式显示数据库中book 表的所有信息,同时提供超链接。
3.需要建立另外的Servlet,用来完成数据库books表的字段的修改。
4.Servlet 后面可以跟键/值对的字符串,多个键 /值对可以使用“&”符号隔开。
打开IE,在浏览器的地址栏里输入:“http://127.0.0.1:8080/SessionTraceDemo2/showBookServlet”。则显示如下图:
当用户点击图书编号超链接时,则显示如下图:
当用户修改图书单价或者是数量时,点击“修改”按钮,则显示如下图
以下是一个可能的MVC模式的实现,其中使用了JSP、Servlet和JavaBean来实现对books表的增、删、改、查操作:
创建MySQL数据库,并在其中创建books表,包含以下字段:ISBN编号、书名、作者、价格和库存数量。
创建JavaBean类Book,用来表示books表中的一条记录。Book类的定义如下:
java
Copy
public class Book {
private String isbn;
private String title;
private String author;
private double price;
private int stock;
public Book() {}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
}
创建DAO类BookDAO,用来完成对books表的增、删、改、查操作,代码如下:
java
Copy
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BookDAO {
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydb";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "123456";
public List<Book> getAllBooks() {
List<Book> books = new ArrayList<>();
try {
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM books");
while (rs.next()) {
Book book = new Book();
book.setIsbn(rs.getString("isbn"));
book.setTitle(rs.getString("title"));
book.setAuthor(rs.getString("author"));
book.setPrice(rs.getDouble("price"));
book.setStock(rs.getInt("stock"));
books.add(book);
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return books;
}
public void updateBook(String isbn, int stock, double price) {
try {
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
PreparedStatement stmt = conn.prepareStatement("UPDATE books SET stock = ?, price = ? WHERE isbn = ?");
stmt.setInt(1, stock);
stmt.setDouble(2,price);
stmt.setString(3, isbn);
stmt.executeUpdate();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
创建Servlet类BookServlet,用来以表格的形式显示books表中的所有记录,并提供超链接,代码如下:
java
Copy
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BookServlet extends HttpServlet {
private BookDAO bookDAO;
public void init() {
bookDAO = new BookDAO();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Book> books = bookDAO.getAllBooks();
request.setAttribute("books", books);
request.getRequestDispatcher("/booklist.jsp").forward(request, response);
}
}
创建JSP页面booklist.jsp,用来显示books表中的所有记录和提供修改链接,代码如下:
jsp
Copy
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Books</title>
</head>
<body>
<h1>Books</h1>
<table border="1">
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
<th>Stock</th>
<th>Action</th>
</tr>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.isbn}</td>
<td>${book.title}</td>
<td>${book.author}</td>
<td>${book.price}</td>
<td>${book.stock}</td>
<td><a href="updatebook.jsp?isbn=${book.isbn}">Update</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
创建JSP页面updatebook.jsp,用来修改books表中某条记录的库存数量和价格,代码如下:
jsp
Copy
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Update Book</title>
</head>
<body>
<h1>Update Book</h1>
<form method="post" action="updatebook">
<label>ISBN:</label>
<input type="text" name="isbn" value="${param.isbn}" readonly><br>
<label>Stock:</label>
<input type="text" name="stock" value="${param.stock}"><br>
<label>Price:</label>
<input type="text" name="price" value="${param.price}"><br>
<input type="submit" value="Update">
</form>
</body>
</html>
最后创建Servlet类UpdateBookServlet,用来处理updatebook.jsp页面提交的表单数据,并调用BookDAO的updateBook方法来更新books表中的某条记录,代码如下:
java
Copy
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateBookServlet extends HttpServlet {
private BookDAO bookDAO;
public void init() {
bookDAO = new BookDAO();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String isbn = request.getParameter("isbn");
int stock = Integer.parseInt(request.getParameter("stock"));
double price = Double.parseDouble(request.getParameter("price"));
bookDAO.updateBook(isbn, stock, price);
response.sendRedirect("book");
}
}
以上是一个简单的使用MVC模式实现对books表的增、删、改、查操作的示例。需要注意的是,这只是一个基础的示例,实际应用中可能需要更加复杂的逻辑和功能,例如添加数据校验、权限控制、分页查询等功能。
可以的,需要发完整项目给你吗
这是比较早的类型,现在做jsp的真不多
可以借鉴下
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.entity.ShopCarItem" %>
<%@ page import="java.util.List" %>
<%@ page import="com.entity.User" %>
<%@ page import="com.myUtil.ProcessUtil" %>
<%@ page import="com.entity.Cart" %><%--
Created by IntelliJ IDEA.
User: huawei
Date: 2022/10/18
Time: 13:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>购物车</title>
<script type="text/javascript" src="script/jquery-3.6.0.min.js"></script>
<!-- 新 Bootstrap5 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css">
<!-- popper.min.js 用于弹窗、提示、下拉菜单 -->
<script src="https://cdn.staticfile.org/popper.js/2.9.3/umd/popper.min.js"></script>
<!-- 最新的 Bootstrap5 核心 JavaScript 文件 -->
<script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
// 清空购物车
$("#removeAll").click(
function () {
if (confirm("是否清空购物车") == true) {
$.post(
"/MyProject/cartProcessServlet",
{
method: "removeAll"
},
function (data) {
if ("success" == data){
location.reload(true);
}
},
"json"
)
} else {
return false;
}
}
)
// 数量加按钮
$("button[id^='numSum_']").click(
function (e) {
var goodId = e.target.id;
// 获取对应的数量值
var $number = $(document.getElementById("number_" + goodId.split("_")[1]));
$number.val(parseInt($number.val()) + 1);
var val = $number.val();
// 将修改后的值写入数据库
sendAjax(goodId,val);
}
)
// 数量减按钮
$("button[id^='numSub_']").click(
function (e) {
var goodId = e.target.id;
// 获取对应的数量值
var $number = $(document.getElementById("number_" + goodId.split("_")[1]));
if ((parseInt($number.val()) -1) >= 1){
$number.val((parseInt($number.val()) -1));
sendAjax(goodId,$number.val());
}
}
)
// 数值框内容变化监听
$("input[id^='number_']").blur(
function(e){
var id = e.target.id;
var val = $(document.getElementById("number_" + e.target.id.split("_")[1])).val();
if (!((/^[1-9]*[1-9][0-9]*$/).test(val))){ //如果不是是正整数
$(document.getElementById("number_" + e.target.id.split("_")[1])).val(1)
}
sendAjax(id,val);
})
// 发送Ajax请求(用于更改购物项信息)
var sendAjax = function (goodId,count) {
$.post(
"/MyProject/cartProcessServlet",
{
method: "updateShopCartItem",
goodId: goodId,
number: count
},
function (data) {
if ("success" == data){
location.reload(true);
}
},
"json"
)
}
// 删除购物项
$("button[id^='delete_']").click(
function (e) {
var goodId = e.target.id.split("_")[1];
$.post(
"/MyProject/cartProcessServlet",
{
method: "removeShopItem",
goodId: goodId
},
function (data) {
if ("success" == data){
location.reload(true);
}
},
"json"
)
}
)
// 结算
$("#settlement").click(
function () {
$.post(
"/MyProject/orderProcessServlet",
{
method: ""
},
function (data) {
if ("success" == data){
alert("订单生成成功!");
location.reload(true);
}
},
"json"
)
}
)
})
</script>
</head>
<body>
<%
session.setAttribute("totalPrice",0.0);
%>
<%--头部导航栏--%>
<nav class="navbar-expand-lg navbar navbar-dark bg-primary">
<div class="container-fluid ">
<a class="navbar-brand" href="#">购物车</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/MyProject/index.jsp">Home</a>
</li>
</ul>
</div>
</div>
</nav>
<c:if test="${empty sessionScope.cart.items}">
<div class="container" >
<div class="card position-relative" style="margin: 50px;height: 280px;background: #ffffff url(img/CartBackground.png) no-repeat; background-position: center left;">
<div class="position-absolute top-50 start-50 translate-middle">
<h7>
您的购物车还是空的,赶紧行动吧!您可以:
</h7><br>
<a class="btn btn-primary btn-lg" href="/MyProject/index.jsp">购物</a>
</div>
</div>
</div>
</c:if>
<c:if test="${!empty sessionScope.cart.items}">
<div class="container">
<div class="card">
<table class="table table-hover text-center">
<tr>
<td>商品</td>
<td>单价</td>
<td>商品数量</td>
<td>总价</td>
<td>操作</td>
</tr>
<c:forEach items="${sessionScope.cart.items}" var="shopCarItem">
<tr style="vertical-align: middle !important;text-align: center;">
<td>
<img style="width: 100px;height: 100px" src="${shopCarItem.value.img}"/>
<span>${shopCarItem.value.goodsName}</span>
</td>
<td>${shopCarItem.value.price}</td>
<td class="col-lg-2">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="numSub_${shopCarItem.value.goodsId}">-</button>
</span>
<input type="text" class="form-control text-center" id="number_${shopCarItem.value.goodsId}" value="${shopCarItem.value.number}">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="numSum_${shopCarItem.value.goodsId}">+</button>
</span>
</div>
</td>
<td>${shopCarItem.value.totalPrice}</td>
<%--计算总价格--%>
<c:set scope="session" value="${sessionScope.totalPrice + shopCarItem.value.totalPrice}" var="totalPrice"></c:set>
<td><button class="btn btn-danger" id="delete_${shopCarItem.value.goodsId}">删除</button></td>
</tr>
</c:forEach>
</table>
<div class="row justify-content-between">
<div class="col-4 m-auto">
<a class="btn btn-primary btn-lg" href="/MyProject/index.jsp">
继续购物
</a>
</div>
<div class="col-4">
<button type="button" class="btn btn-warning btn-lg" id="removeAll">清空购物车</button>
<span>
<span class="fs-3">
合计
</span>
<span class="fs-3 fw-bold" id="total" style="color: red">
${sessionScope.totalPrice}
<button type="button" class="btn btn-dark " id="settlement">结算</button>
</span>
</span>
</div>
</div>
</div>
</div>
</c:if>
<div class="container">
<%--footer--%>
<div class="row align-items-end">
<footer class="py-5" >
<div class="row">
<div class="col-2">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
<div class="col-2">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
<div class="col-2">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
</div>
<div class="d-flex justify-content-between py-4 my-4 border-top">
<p>© 2021 Company, Inc. All rights reserved.</p>
<ul class="list-unstyled d-flex">
<li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#twitter"/></svg></a></li>
<li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#instagram"/></svg></a></li>
<li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#facebook"/></svg></a></li>
</ul>
</div>
</footer>
</div>
</div>
</body>
</html>
首先需要创建一个books表,表结构如下:
```bash
CREATE TABLE `books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`isbn` varchar(13) NOT NULL,
`title` varchar(100) NOT NULL,
`author` varchar(50) NOT NULL,
`price` decimal(10,2) NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
接下来,需要创建一个JavaBean来表示书籍信息
接下来,创建一个DAO类来连接数据库并实现对books表的操作。
public class Book {
private int id;
private String isbn;
private String title;
private String author;
private double price;
private int quantity;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
public class BookDAO {
private String jdbcUrl = "jdbc:mysql://localhost:3306/mydb";
private String jdbcUsername = "root";
private String jdbcPassword = "password";
private Connection connection;
public BookDAO() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addBook(Book book) {
String sql = "INSERT INTO books(isbn, title, author, price, quantity) VALUES (?, ?, ?, ?, ?)";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, book.getIsbn());
statement.setString(2, book.getTitle());
statement.setString(3, book.getAuthor());
statement.setDouble(4, book.getPrice());
statement.setInt(5, book.getQuantity());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateBook(Book book) {
String sql = "UPDATE books SET quantity = ?, price = ? WHERE isbn = ?";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, book.getQuantity());
statement.setDouble(2, book.getPrice());
statement.setString(3, book.getIsbn());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Book getBook(String isbn) {
String sql = "SELECT * FROM books WHERE isbn = ?";
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, isbn);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
Book book = new Book();
book.setId(resultSet.getInt("id"));
book.setIsbn(resultSet.getString("isbn"));
book.setTitle(resultSet.getString("title"));
book.setAuthor(resultSet.getString("author"));
book.setPrice(resultSet.getDouble("price"));
book.setQuantity(resultSet.getInt("quantity"));
return book;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
接下来,在Servlet中调用上述DAO类的方法来实现对books表的操作。
```java
@WebServlet("/updateBook")
public class UpdateBookServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String isbn = request.getParameter("isbn");
int quantity = Integer.parseInt(request.getParameter("quantity"));
double price = Double.parseDouble(request.getParameter("price"));
BookDAO bookDAO = new BookDAO();
Book book = bookDAO.getBook(isbn);
if (book != null) {
book.setQuantity(quantity);
book.setPrice(price);
bookDAO.updateBook(book);
}
response.sendRedirect(request.getContextPath() + "/bookList.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
最后,在JSP页面中创建一个表单用于更新书籍信息。
```html
<form action="updateBook" method="post">
<label>ISBN:</label>
<input type="text" name="isbn">
<br>
<label>Quantity:</label>
<input type="text" name="quantity">
<br>
<label>Price:</label>
<input type="text" name="price">
<br>
<input type="submit" value="Update">
</form>
```
使用MVC模式实现图书信息管理系统需要使用JSP、Servlet和JavaBean来完成数据库的相关操作。具体步骤如下:
创建MySQL数据库,建立books表,存储图书相关信息,如ISBN编号、书名、作者、价格和库存数量等信息。
创建JavaBean类,编写与数据库books表对应的数据类型、属性和get/set方法。
创建业务类BookService,实现数据库books表的增删改查方法,供Servlet调用。
创建Servlet,实现以下功能:
a. 创建Table,以表格的形式显示books表的所有信息。
b. 使用超链接传递图书编号信息,跳转到bookEdit.jsp界面,允许对图书信息进行修改。
c. 实现bookEdit.jsp中的修改功能,即修改图书单价或者是数量,并且更新到数据库中。
创建bookEdit.jsp界面,实现以下功能:
a. 显示已选图书的相关信息。
b. 允许用户修改图书单价或者是数量,并且提交修改请求。
c. 提供返回按钮,返回到Table中。
jsp页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.entity.ShopCarItem" %>
<%@ page import="java.util.List" %>
<%@ page import="com.entity.User" %>
<%@ page import="com.myUtil.ProcessUtil" %>
<%@ page import="com.entity.Cart" %><%--
Created by IntelliJ IDEA.
User: huawei
Date: 2022/10/18
Time: 13:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>购物车</title>
<script type="text/javascript" src="script/jquery-3.6.0.min.js"></script>
<!-- 新 Bootstrap5 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css">
<!-- popper.min.js 用于弹窗、提示、下拉菜单 -->
<script src="https://cdn.staticfile.org/popper.js/2.9.3/umd/popper.min.js"></script>
<!-- 最新的 Bootstrap5 核心 JavaScript 文件 -->
<script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
// 清空购物车
$("#removeAll").click(
function () {
if (confirm("是否清空购物车") == true) {
$.post(
"/MyProject/cartProcessServlet",
{
method: "removeAll"
},
function (data) {
if ("success" == data){
location.reload(true);
}
},
"json"
)
} else {
return false;
}
}
)
// 数量加按钮
$("button[id^='numSum_']").click(
function (e) {
var goodId = e.target.id;
// 获取对应的数量值
var $number = $(document.getElementById("number_" + goodId.split("_")[1]));
$number.val(parseInt($number.val()) + 1);
var val = $number.val();
// 将修改后的值写入数据库
sendAjax(goodId,val);
}
)
// 数量减按钮
$("button[id^='numSub_']").click(
function (e) {
var goodId = e.target.id;
// 获取对应的数量值
var $number = $(document.getElementById("number_" + goodId.split("_")[1]));
if ((parseInt($number.val()) -1) >= 1){
$number.val((parseInt($number.val()) -1));
sendAjax(goodId,$number.val());
}
}
)
// 数值框内容变化监听
$("input[id^='number_']").blur(
function(e){
var id = e.target.id;
var val = $(document.getElementById("number_" + e.target.id.split("_")[1])).val();
if (!((/^[1-9]*[1-9][0-9]*$/).test(val))){ //如果不是是正整数
$(document.getElementById("number_" + e.target.id.split("_")[1])).val(1)
}
sendAjax(id,val);
})
// 发送Ajax请求(用于更改购物项信息)
var sendAjax = function (goodId,count) {
$.post(
"/MyProject/cartProcessServlet",
{
method: "updateShopCartItem",
goodId: goodId,
number: count
},
function (data) {
if ("success" == data){
location.reload(true);
}
},
"json"
)
}
// 删除购物项
$("button[id^='delete_']").click(
function (e) {
var goodId = e.target.id.split("_")[1];
$.post(
"/MyProject/cartProcessServlet",
{
method: "removeShopItem",
goodId: goodId
},
function (data) {
if ("success" == data){
location.reload(true);
}
},
"json"
)
}
)
// 结算
$("#settlement").click(
function () {
$.post(
"/MyProject/orderProcessServlet",
{
method: ""
},
function (data) {
if ("success" == data){
alert("订单生成成功!");
location.reload(true);
}
},
"json"
)
}
)
})
</script>
</head>
<body>
<%
session.setAttribute("totalPrice",0.0);
%>
<%--头部导航栏--%>
<nav class="navbar-expand-lg navbar navbar-dark bg-primary">
<div class="container-fluid ">
<a class="navbar-brand" href="#">购物车</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/MyProject/index.jsp">Home</a>
</li>
</ul>
</div>
</div>
</nav>
<c:if test="${empty sessionScope.cart.items}">
<div class="container" >
<div class="card position-relative" style="margin: 50px;height: 280px;background: #ffffff url(img/CartBackground.png) no-repeat; background-position: center left;">
<div class="position-absolute top-50 start-50 translate-middle">
<h7>
您的购物车还是空的,赶紧行动吧!您可以:
</h7><br>
<a class="btn btn-primary btn-lg" href="/MyProject/index.jsp">购物</a>
</div>
</div>
</div>
</c:if>
<c:if test="${!empty sessionScope.cart.items}">
<div class="container">
<div class="card">
<table class="table table-hover text-center">
<tr>
<td>商品</td>
<td>单价</td>
<td>商品数量</td>
<td>总价</td>
<td>操作</td>
</tr>
<c:forEach items="${sessionScope.cart.items}" var="shopCarItem">
<tr style="vertical-align: middle !important;text-align: center;">
<td>
<img style="width: 100px;height: 100px" src="${shopCarItem.value.img}"/>
<span>${shopCarItem.value.goodsName}</span>
</td>
<td>${shopCarItem.value.price}</td>
<td class="col-lg-2">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="numSub_${shopCarItem.value.goodsId}">-</button>
</span>
<input type="text" class="form-control text-center" id="number_${shopCarItem.value.goodsId}" value="${shopCarItem.value.number}">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="numSum_${shopCarItem.value.goodsId}">+</button>
</span>
</div>
</td>
<td>${shopCarItem.value.totalPrice}</td>
<%--计算总价格--%>
<c:set scope="session" value="${sessionScope.totalPrice + shopCarItem.value.totalPrice}" var="totalPrice"></c:set>
<td><button class="btn btn-danger" id="delete_${shopCarItem.value.goodsId}">删除</button></td>
</tr>
</c:forEach>
</table>
<div class="row justify-content-between">
<div class="col-4 m-auto">
<a class="btn btn-primary btn-lg" href="/MyProject/index.jsp">
继续购物
</a>
</div>
<div class="col-4">
<button type="button" class="btn btn-warning btn-lg" id="removeAll">清空购物车</button>
<span>
<span class="fs-3">
合计
</span>
<span class="fs-3 fw-bold" id="total" style="color: red">
${sessionScope.totalPrice}
<button type="button" class="btn btn-dark " id="settlement">结算</button>
</span>
</span>
</div>
</div>
</div>
</div>
</c:if>
<div class="container">
<%--footer--%>
<div class="row align-items-end">
<footer class="py-5" >
<div class="row">
<div class="col-2">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
<div class="col-2">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
<div class="col-2">
<h5>Section</h5>
<ul class="nav flex-column">
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Home</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Features</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">Pricing</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">FAQs</a></li>
<li class="nav-item mb-2"><a href="#" class="nav-link p-0 text-muted">About</a></li>
</ul>
</div>
</div>
<div class="d-flex justify-content-between py-4 my-4 border-top">
<p>© 2021 Company, Inc. All rights reserved.</p>
<ul class="list-unstyled d-flex">
<li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#twitter"/></svg></a></li>
<li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#instagram"/></svg></a></li>
<li class="ms-3"><a class="link-dark" href="#"><svg class="bi" width="24" height="24"><use xlink:href="#facebook"/></svg></a></li>
</ul>
</div>
</footer>
</div>
</div>
</body>
</html>
该回答引用GPT与博主@晓码自在合作编写:
根据问题描述,这里是Java web程序的实现步骤:
sql
CREATE TABLE books (
id INT PRIMARY KEY AUTO_INCREMENT,
isbn VARCHAR(50),
name VARCHAR(50),
author VARCHAR(50),
price DOUBLE,
count INT
)
java
public class Book {
private int id;
private String isbn;
private String name;
private String author;
private double price;
private int count;
//getter和setter方法...
}
java
public class BookDao {
//查询所有书籍
public List<Book> queryAllBooks() {...}
//更新书籍价格和库存
public void updateBook(int id, double price, int count) {...}
}
java
public class BookServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BookDao dao = new BookDao();
List<Book> books = dao.queryAllBooks();
PrintWriter out = resp.getWriter();
out.print("<table>");
for (Book book : books) {
out.print("<tr><td>");
out.print("<a href='/update?id=" + book.getId() + "'>");
out.print(book.getName());
out.print("</a></td></tr>");
}
out.print("</table>");
}
}
java
public class UpdateServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = Integer.parseInt(req.getParameter("id"));
double price = Double.parseDouble(req.getParameter("price"));
int count = Integer.parseInt(req.getParameter("count"));
BookDao dao = new BookDao();
dao.updateBook(id, price, count);
resp.sendRedirect("/book");
}
}
这就是使用MVC模式和JDBC实现书籍信息更新的Java web程序的具体步骤和代码实现。
以下答案由GPT-3.5大模型与博主波罗歌共同编写:
首先,我们在MySQL中创建一个名为"bookstore"的数据库,并创建一个名为"books"的表,其中存储图书的信息。表的结构如下:
CREATE TABLE `books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ISBN` varchar(45) NOT NULL,
`name` varchar(255) NOT NULL,
`author` varchar(255) NOT NULL,
`price` double NOT NULL,
`inventory` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
我们需要创建一个名为"Book"的JavaBean类,用来表示一本书的信息。它应该包括以下属性:ISBN编号、书名、作者、价格、库存数量等。
public class Book {
private int id;
private String ISBN;
private String name;
private String author;
private double price;
private int inventory;
public Book() {}
public Book(int id, String ISBN, String name, String author, double price, int inventory) {
this.id = id;
this.ISBN = ISBN;
this.name = name;
this.author = author;
this.price = price;
this.inventory = inventory;
}
// getter and setter methods
}
接下来,我们需要创建一个DAO类和一个Service类,用来操作数据库中的书籍信息。
BookDAO.java:
public class BookDAO {
private Connection conn;
public BookDAO(Connection conn) {
this.conn = conn;
}
// 获取全部书籍信息
public List<Book> getAllBooks() throws SQLException {
String sql = "SELECT * FROM books";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
List<Book> books = new ArrayList<>();
while (rs.next()) {
Book book = new Book(rs.getInt("id"), rs.getString("ISBN"), rs.getString("name"),
rs.getString("author"), rs.getDouble("price"), rs.getInt("inventory"));
books.add(book);
}
rs.close();
pstmt.close();
return books;
}
// 更新书籍信息
public boolean updateBook(int id, double price, int inventory) throws SQLException {
String sql = "UPDATE books SET price = ?, inventory = ? WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setDouble(1, price);
pstmt.setInt(2, inventory);
pstmt.setInt(3, id);
int rows = pstmt.executeUpdate();
pstmt.close();
return rows > 0;
}
}
BookService.java:
public class BookService {
private BookDAO bookDAO;
public BookService(BookDAO bookDAO) {
this.bookDAO = bookDAO;
}
// 获取全部书籍信息
public List<Book> getAllBooks() throws SQLException {
return bookDAO.getAllBooks();
}
// 更新书籍信息
public boolean updateBook(int id, double price, int inventory) throws SQLException {
return bookDAO.updateBook(id, price, inventory);
}
}
最后,我们需要创建一个Servlet,用来以表格的形式显示数据库中book表的所有信息,并提供修改图书信息的功能。
ShowBookServlet.java:
public class ShowBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应的内容类型
response.setContentType("text/html; charset=UTF-8");
// 获取所有书籍信息
List<Book> books;
try {
Connection conn = DBUtil.getConnection();
BookDAO bookDAO = new BookDAO(conn);
BookService bookService = new BookService(bookDAO);
books = bookService.getAllBooks();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
books = new ArrayList<>();
}
// 显示所有书籍信息
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>图书列表</title></head>");
out.println("<body>");
out.println("<h1>图书列表</h1>");
out.println("<table border='1'>");
out.println("<tr><th>ID</th><th>ISBN</th><th>书名</th><th>作者</th>"
+ "<th>价格</th><th>库存数量</th><th>修改</th></tr>");
for (Book book : books) {
out.println("<tr>");
out.println("<td>" + book.getId() + "</td>");
out.println("<td>" + book.getISBN() + "</td>");
out.println("<td>" + book.getName() + "</td>");
out.println("<td>" + book.getAuthor() + "</td>");
out.println("<td>" + book.getPrice() + "</td>");
out.println("<td>" + book.getInventory() + "</td>");
out.println("<td><a href='updateBookServlet?id=" + book.getId() + "'>修改</a></td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
UpdateBookServlet.java:
public class UpdateBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应的内容类型
response.setContentType("text/html; charset=UTF-8");
// 获取要修改的书的ID
int id = Integer.parseInt(request.getParameter("id"));
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>修改图书信息</title></head>");
out.println("<body><h1>修改图书信息</h1>");
// 获取该书的信息
Book book;
try {
Connection conn = DBUtil.getConnection();
BookDAO bookDAO = new BookDAO(conn);
book = bookDAO.getBookById(id);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
book = null;
}
if (book == null) {
out.println("<p>该书不存在!</p>");
} else {
// 显示该书的详细信息,并提供修改功能
out.println("<form action='updateBookActionServlet?id=" + id + "' method='post'>");
out.println("<table>");
out.println("<tr><td>ISBN编号:</td><td>" + book.getISBN() + "</td></tr>");
out.println("<tr><td>书名:</td><td>" + book.getName() + "</td></tr>");
out.println("<tr><td>作者:</td><td>" + book.getAuthor() + "</td></tr>");
out.println("<tr><td>价格:</td><td><input type='text' name='price' value='"
+ book.getPrice() + "'></td></tr>");
out.println("<tr><td>库存数量:</td><td><input type='text' name='inventory' value='"
+ book.getInventory() + "'></td></tr>");
out.println("<tr><td colspan='2'><input type='submit' value='修改'></td></tr>");
out.println("</table>");
out.println("</form>");
}
out.println("</body>");
out.println("</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
UpdateBookActionServlet.java:
public class UpdateBookActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取要修改的书的ID和修改后的信息
int id = Integer.parseInt(request.getParameter("id"));
double price = Double.parseDouble(request.getParameter("price"));
int inventory = Integer.parseInt(request.getParameter("inventory"));
// 更新书籍信息
try {
Connection conn = DBUtil.getConnection();
BookDAO bookDAO = new BookDAO(conn);
bookDAO.updateBook(id, price, inventory);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 显示修改结果
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>修改结果</title></head>");
out.println("<body><h1>修改结果</h1>");
out.println("<p>修改成功!</p>");
out.println("<a href='showBookServlet'>返回</a>");
out.println("</body>");
out.println("</html>");
}
}
其中,我们使用了DBUtil类来获取数据库连接。
DBUtil.java:
public class DBUtil {
private DBUtil() {}
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/bookstore?useSSL=false";
private static final String USER = "root";
private static final String PASSWORD = "root";
public static Connection getConnection() throws SQLException {
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
System.err.println("无法加载数据库驱动!");
e.printStackTrace();
}
return conn;
}
}
最后,我们需要创建一个JSP页面,通过超链接来访问ShowBookServlet。
bookstore.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书管理系统</title>
</head>
<body>
<h1>图书管理系统</h1>
<a href="showBookServlet">查看图书列表</a>
</body>
</html>
将所有的Java类和JSP页面都打成WAR包,然后将该WAR包部署到Tomcat服务器中运行。在浏览器中输入"http://localhost:8080/bookstore/bookstore.jsp",即可访问我们的图书管理系统了。
以上就是Java Web服务器端购物车系统的实现,希望对你有所帮助。
如果我的回答解决了您的问题,请采纳!