目录
实现效果
源代码
数据库文件
结语
实现效果
源代码
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<title>登录界面</title>
<form action="login.jsp" method="post" onsubmit="return isLogin()">
<div>
<div>
<input type="text" class="form-control" name="username" id="username"
placeholder="请输入账号">
<input type="text" class="form-control" name="password" id="password"
placeholder="请输入密码">
</div>
<br><button type="submit">Login</button>
</div>
</form>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC";
String user = "root";
String pass = "123456";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pass);
String sql = "SELECT * FROM user WHERE username=? AND password=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
session.setAttribute("username", username);
response.sendRedirect("index.jsp");
} else {
out.println("<p>用户名或密码错误,请重新登录</p>");
}
rs.close();
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>购物商城</title>
</head>
<body>
<h1>购物商城</h1>
<p>
欢迎:<font color="red"><%=session.getAttribute("username")%></font>
</p>
<ul>
<li><a href="#" class="active"><i class="fa fa-home fa-fw"></i>商品管理</a></li>
<li><a href="userinfo.jsp"><i class="fa fa-bar-chart fa-fw"></i>用户管理</a></li>
<li><a href="addcart.jsp"><i class="fa fa-bar-chart fa-fw"></i>购物车</a></li>
<li><a href="login.jsp"><i class="fa fa-sliders fa-fw"></i>登出</a></li>
</ul>
<table>
<thead>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<%
// 连接数据库
String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM product");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>" + rs.getString("name") + "</td><td>"
+ rs.getDouble("price") + "</td>"+"<td>" + "<a href='addcartdo.jsp?id=" + rs.getInt(1)
+ "' class='templatemo-edit-btn'>添加到购物车<a></td>"+"<td>" + "<a href='modpro.jsp?id=" + rs.getInt(1)
+ "' class='templatemo-edit-btn'>修改<a></td>" + "<td><a href='javascript:del(" + rs.getInt(1)
+ ")' class='templatemo-link'>删除<a>" + "</td></tr>");
}
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
</tbody>
</table>
<script>
function del(id) {
var flag = confirm("确认删除?");
if (flag) {
window.location.href = "delpro.jsp?id=" + id;
}
}
</script>
</body>
</html>
userinfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>购物商城</title>
</head>
<body>
<h1>购物商城</h1>
<p>
欢迎:<font color="red"><%=session.getAttribute("username")%></font>
</p>
<ul>
<li><a href="index.jsp" ><i class="fa fa-home fa-fw"></i>商品管理</a></li>
<li><a href="userinfo.jsp" class="active"><i class="fa fa-bar-chart fa-fw"></i>用户管理</a></li>
<li><a href="addcart.jsp"><i class="fa fa-bar-chart fa-fw"></i>购物车</a></li>
<li><a href="login.jsp"><i class="fa fa-sliders fa-fw"></i>登出</a></li>
</ul>
<table>
<thead>
<tr>
<th>用户编号</th>
<th>用户名称</th>
<th>password</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<%
// 连接数据库
String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM user");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>" + rs.getString("username") + "</td><td>"
+ rs.getString("password") + "</td>" + "<td><a>不可删除<a>" + "</td></tr>");
}
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
</tbody>
</table>
<script>
</script>
</body>
</html>
addcart.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>购物车列表</title>
</head>
<body>
<h1>购物车列表</h1>
<p>
欢迎:<font color="red"><%=session.getAttribute("username")%></font>
</p>
<ul>
<li><a href="index.jsp"><i class="fa fa-home fa-fw"></i>商品管理</a></li>
<li><a href="userinfo.jsp"><i class="fa fa-bar-chart fa-fw"></i>用户管理</a></li>
<li><a href="#" class="active"><i class="fa fa-bar-chart fa-fw"></i>购物车</a></li>
<li><a href="login.jsp"><i class="fa fa-sliders fa-fw"></i>登出</a></li>
</ul>
<table>
<thead>
<tr>
<th>购物人编号</th>
<th>购物人</th>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
</tr>
</thead>
<tbody>
<%
// 连接数据库
String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM cart");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>" + rs.getString("username") + "</td><td>"+rs.getInt("productid")+"</td><td>"
+ rs.getString("name") + "</td><td>" + rs.getDouble("price") + "</td></tr>");
}
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
</tbody>
</table>
<script>
function del(id) {
var flag = confirm("确认删除?");
if (flag) {
window.location.href = "delcart.jsp?id=" + id;
}
}
</script>
</body>
</html>
addcartdo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page import="javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>购物车列表</title>
</head>
<body>
<h1>购物车列表</h1>
<p>
欢迎:<font color="red"><%=session.getAttribute("username")%></font>
</p>
<table>
<tbody>
<%
Connection conn2 = null;
PreparedStatement pstmt2 = null;
String userid;
String username= (String)session.getAttribute("username");
Class.forName("com.mysql.cj.jdbc.Driver");
conn2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
Statement stm = conn2.createStatement();
ResultSet rs2 = stm.executeQuery("select id from user where username='"+username+"'");
if(rs2.next()){
userid = rs2.getString(1);
Connection conn = null;
Connection conn1 = null;
PreparedStatement pstmt = null;
String Proname;
Double Proprice;
int productId = Integer.parseInt(request.getParameter("id"));
Class.forName("com.mysql.jdbc.Driver");
conn1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
Statement stmt = conn1.createStatement();
ResultSet rs1 = stmt.executeQuery("select name,price from product where id=" +productId);
while(rs1.next()){
Proname = rs1.getString(1);
Proprice = rs1.getDouble(2);
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
String sql = "INSERT INTO cart VALUES (?, ?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(userid));
pstmt.setString(2,username);
pstmt.setInt(3, productId);
pstmt.setString(4, Proname);
pstmt.setDouble(5, Proprice);
pstmt.executeUpdate();
out.print("加入购物车成功!");
out.print("");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null) {
pstmt.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
%>
</tbody>
<a href="addcart.jsp">返回购物车</a>
</table>
</body>
</html>
modpro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert use here</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("id"));
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String phonename ="";
double phoneprice=0;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
String sql = "SELECT name, price FROM product WHERE id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
phonename = rs.getString("name");
phoneprice = rs.getDouble("price");
} else {
out.print("没有找到该商品!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) {
rs.close();
}
if(pstmt != null) {
pstmt.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
<h1>商品编号为<%=id%></h1>
<form action="modprodo.jsp?id=<%=id%>" method="post">
<div>
<div>
<label for="name">名称</label> <input type="text"
class="form-control" name="name" id="name"
placeholder="请输入名称" value="<%=phonename%>">
</div>
<div>
<label for="price">价格</label> <input type="text"
class="form-control" name="price" id="price"
placeholder="请输入价格" value="<%=phoneprice%>">
</div>
</div>
<div class="form-group text-right">
<button type="submit" class="templatemo-blue-button">提交</button>
<button type="reset" class="templatemo-white-button">重置</button>
</div>
</form>
</body>
</html>
modprodo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%
String name = request.getParameter("name");
double price = Double.parseDouble(request.getParameter("price"));
int id = Integer.parseInt(request.getParameter("id"));
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=UTF-8", "root", "123456");
String sql = "UPDATE product SET price=? ,name=? where id="+id;
pstmt = conn.prepareStatement(sql);
pstmt.setDouble(1, price);
pstmt.setString(2, name);
pstmt.executeUpdate();
out.print("更新成功!");
response.sendRedirect("index.jsp");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(pstmt != null) {
pstmt.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
delpro.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
<%@page import="javax.naming.*"%>
<%
String id = request.getParameter("id");
if (id != null) {
String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
pstmt = conn.prepareStatement("SELECT * FROM product WHERE id=?");
pstmt.setInt(1, Integer.parseInt(id));
rs = pstmt.executeQuery();
if (rs.next()) {
pstmt = conn.prepareStatement("DELETE FROM product WHERE id=?");
pstmt.setInt(1, rs.getInt("id"));
pstmt.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
%>
<html>
<head>
<meta charset="UTF-8">
<title>Delete Pro</title>
</head>
<body>
<h1>Delete Pro</h1>
<% if (id != null) { %>
<p>id=<%=id%> 的商品已经被删除!</p>
<a href="index.jsp">返回主页面</a>
<% } else { %>
<p>No user has been deleted.</p>
<% } %>
</body>
数据库文件
shop.sql文章来源:https://www.toymoban.com/news/detail-779224.html
/*
Navicat Premium Data Transfer
Source Server : tuomasi
Source Server Type : MySQL
Source Server Version : 80023
Source Host : localhost:3306
Source Schema : shop
Target Server Type : MySQL
Target Server Version : 80023
File Encoding : 65001
Date: 10/04/2023 22:13:56
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for cart
-- ----------------------------
DROP TABLE IF EXISTS `cart`;
CREATE TABLE `cart` (
`id` int(0) NOT NULL,
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`productid` int(0) NOT NULL,
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`price` double NOT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for product
-- ----------------------------
DROP TABLE IF EXISTS `product`;
CREATE TABLE `product` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`price` decimal(8, 2) NOT NULL,
`stock` int(0) NOT NULL,
`description` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of product
-- ----------------------------
INSERT INTO `product` VALUES (1, 'iPhone 12 Pro', 9999.00, 100, 'A14 Bionic chip, 5G, Ceramic Shield, Pro camera system, LiDAR scanner');
INSERT INTO `product` VALUES (2, 'MacBook Pro', 14999.00, 50, 'Apple M1 chip, 8-core CPU, 8-core GPU, 16GB unified memory, 512GB SSD storage');
INSERT INTO `product` VALUES (3, 'iPad Pro', 7999.00, 80, 'M1 chip, 12.9-inch Liquid Retina XDR display, 5G, Thunderbolt, Apple Pencil (2nd generation)');
INSERT INTO `product` VALUES (4, 'Apple Watch 6', 3999.00, 120, 'Blood Oxygen app, ECG app, Always-On Retina display, GPS, LTE, 50m water resistance');
INSERT INTO `product` VALUES (5, 'AirPods Pro', 1999.00, 200, 'Active Noise Cancellation, Transparency mode, Adaptive EQ, sweat and water resistant');
INSERT INTO `product` VALUES (6, 'iMac', 11999.00, 30, 'Apple M1 chip, 24-inch 4.5K Retina display, 8-core GPU, 8GB unified memory, 256GB SSD storage');
INSERT INTO `product` VALUES (7, 'HomePod mini', 749.00, 150, 'Siri voice control, Apple Music, Intercom, HomeKit smart home accessories');
INSERT INTO `product` VALUES (8, 'Apple TV 4K', 1699.00, 90, 'A12 Bionic chip, 4K High Frame Rate HDR, Dolby Vision, Siri Remote, Apple Arcade');
INSERT INTO `product` VALUES (9, 'Magic Mouse 2', 549.00, 300, 'Multi-Touch surface, Wireless, Rechargeable, Bluetooth, Lightning to USB Cable');
INSERT INTO `product` VALUES (10, 'AirTag', 229.00, 500, 'Precision Finding, Find My app, Privacy and security, Replaceable battery');
INSERT INTO `product` VALUES (11, 'AirPods Max', 4799.00, 80, 'High-Fidelity Audio, Adaptive EQ, Active Noise Cancellation, Transparency mode');
INSERT INTO `product` VALUES (12, 'MacBook Air', 9499.00, 70, 'Apple M1 chip, 8-core CPU, 7-core GPU, 8GB unified memory, 256GB SSD storage');
INSERT INTO `product` VALUES (13, 'iPad Air', 5999.00, 100, 'A14 Bionic chip, 10.9-inch Liquid Retina display, Touch ID, Apple Pencil (2nd generation)');
INSERT INTO `product` VALUES (14, 'Apple Watch SE', 2599.00, 150, 'Retina display, GPS, LTE, fall detection, heart rate monitoring, sleep tracking');
INSERT INTO `product` VALUES (15, 'iMac Pro', 41999.00, 10, '27-inch Retina 5K display, 10-core Xeon W processor, 32GB memory, 1TB SSD storage, Radeon Pro Vega 56');
INSERT INTO `product` VALUES (16, 'Magic Keyboard', 899.00, 250, 'Full-size keyboard, Numeric keypad, Bluetooth, Rechargeable, Lightning to USB Cable');
INSERT INTO `product` VALUES (17, 'Mac Pro', 63999.00, 5, '3.5GHz 8-core Intel Xeon W processor, 32GB memory, Radeon Pro 580X, 256GB SSD storage');
INSERT INTO `product` VALUES (18, 'HomePod', 1299.00, 100, 'High-fidelity audio, Siri voice control, Apple Music, Intercom, HomeKit smart home accessories');
INSERT INTO `product` VALUES (19, 'Apple TV HD', 699.00, 120, 'A8 chip, 1080p HD, Dolby Digital Plus 7.1 surround sound, Siri Remote, Apple Arcade');
INSERT INTO `product` VALUES (20, 'iPad mini', 3599.00, 80, 'A12 Bionic chip, 7.9-inch Retina display, Touch ID, Apple Pencil (1st generation) support');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'Alice', '123456', 'alice@example.com');
INSERT INTO `user` VALUES (2, 'Bob', 'abcdef', 'bob@example.com');
INSERT INTO `user` VALUES (3, 'Charlie', 'qwerty', 'charlie@example.com');
INSERT INTO `user` VALUES (4, 'David', '123abc', 'david@example.com');
INSERT INTO `user` VALUES (5, 'Eve', 'password', 'eve@example.com');
INSERT INTO `user` VALUES (6, 'Frank', 'hello123', 'frank@example.com');
INSERT INTO `user` VALUES (7, 'Grace', 'abc123xyz', 'grace@example.com');
INSERT INTO `user` VALUES (8, 'Henry', 'p@ssw0rd', 'henry@example.com');
INSERT INTO `user` VALUES (9, 'Irene', 'qwerty123', 'irene@example.com');
INSERT INTO `user` VALUES (10, 'Jack', 'password123', 'jack@example.com');
SET FOREIGN_KEY_CHECKS = 1;
结语
再者,记得把jdbc驱动包加到lib目录下,启动tomcat,购物商城小项目就算完成了文章来源地址https://www.toymoban.com/news/detail-779224.html
到了这里,关于Jsp+mysql实现简易版购物商城(附源码及数据库)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!