Jsp+mysql实现简易版购物商城(附源码及数据库)
作者:mmseoamin日期:2023-12-25

目录

实现效果

源代码

数据库文件

结语


 


实现效果

 

 

 

 

 


源代码

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>
登录界面

<% 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("

用户名或密码错误,请重新登录

"); } 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.*"%>




购物商城


	

购物商城

欢迎:<%=session.getAttribute("username")%>

  • 商品管理
  • 用户管理
  • 购物车
  • 登出
<% // 连接数据库 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(""+""+"" + ""); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } %>
商品编号 商品名称 商品价格 操作
" + rs.getInt("id") + "" + rs.getString("name") + "" + rs.getDouble("price") + "" + "添加到购物车" + "修改删除" + "

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.*"%>




购物商城


	

购物商城

欢迎:<%=session.getAttribute("username")%>

  • 商品管理
  • 用户管理
  • 购物车
  • 登出
<% // 连接数据库 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("" + ""); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } %>
用户编号 用户名称 password 操作
" + rs.getInt("id") + "" + rs.getString("username") + "" + rs.getString("password") + "不可删除" + "

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.*"%>




购物车列表


    

购物车列表

欢迎:<%=session.getAttribute("username")%>

  • 商品管理
  • 用户管理
  • 购物车
  • 登出
<% // 连接数据库 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(""); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } %>
购物人编号 购物人 商品编号 商品名称 商品价格
" + rs.getInt("id") + "" + rs.getString("username") + ""+rs.getInt("productid")+"" + rs.getString("name") + "" + rs.getDouble("price") + "

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.*"%>




购物车列表


    

购物车列表

欢迎:<%=session.getAttribute("username")%>

<% 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(); } } } } %> 返回购物车

modpro.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*"%>




Insert use here


<%
	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();
        }
    }
%>
            

商品编号为<%=id%>

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();
                }
            }
        }
    }
%>


    
    Delete Pro


    

Delete Pro

<% if (id != null) { %>

id=<%=id%> 的商品已经被删除!

返回主页面 <% } else { %>

No user has been deleted.

<% } %>

数据库文件

shop.sql

/*
 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,购物商城小项目就算完成了