一、需求分析

用JSP/Servlet技术开发一个网上书店,主要完成以下功能:

用户:注册与登录,用户信息的修改

图书:图书显示,图书的购买,购物车的管理。图书的添加,删除,查询

二、系统设计

1)创建相关的数据库表;

2)使用MVC架构或者JSP+JavaBean,至少一个功能模块使用MVC;

3)在JSP中综合使用EL 表达式,JSTL标记库,JavaBean ;

4)使用过滤器完成请求参数编码的设置或登录权限的控制;

5)正确完成Servlet和过滤器的配置

6)使用数据库连接池进行数据库连

三、程序流程图

四、各功能实现代码

4.1管理员功能实现

4.1.1管理员类

4.1.2管理员类dao接口

4.1.3管理员类dao接口的实现方法(操作数据库)

package bean;

import utils.JDBCUtil;

import java.sql.*;

public  class adminDaoImpl implements adminDao{

    public void addadmin(admin a) {
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = "insert into admin value (?,?)";
            conn = JDBCUtil.getConnection();
            psql=conn.prepareStatement(sql);
            psql.setString(1,a.getName());
            psql.setString(2,a.getPassword());
            int i = psql.executeUpdate();
            if(i>0){
                System.out.println("插入成功!");
            }else {
                System.out.println("插入失败!");
            }
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }

    public admin queryadmin(String username) {

        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        admin a=new admin();

        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from admin where name ='" + username + "'";
            rs=statement.executeQuery(sql);
            while(rs.next()){

                a.setName(rs.getString("name"));
                a.setPassword(rs.getString("password"));
            }
            rs.close();
            conn.close();
            return a;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(statement, conn);
        }
        return a;
    }
}

4.1.4管理员登录页面

4.1.5管理员注册页面

4.1.5管理员登录的service方法

import bean.UserDaoImpl;
import bean.adminDao;
import bean.adminDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "adminLoginServlet",urlPatterns = "/adminLoginServlet")
public class adminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置编码和响应类型
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session =request.getSession(true);
        //         1.获得用户名和密码
        //       2.验证用户名和密码是否正确 "zhou" "123456"
        String adminname=request.getParameter("adminName");
        String password=request.getParameter("adminPasswd");
        //获得响应的输出流
        PrintWriter pw=response.getWriter();
        adminDao dao = new adminDaoImpl();
        String name=dao.queryadmin(adminname).getName();
        String passwd=dao.queryadmin(adminname).getPassword();
        if(adminname.equals(name)&&password.equals(passwd)){
            session.setAttribute("admin",name);
            request.getRequestDispatcher("/adminnavcation.jsp").forward(request,response);
        }else {
            //验证失败
            pw.println("<font color='green'><h2>登录失败</h2></font>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

管理员注册的方法

import utils.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(name = "adminRegistServlet",urlPatterns = "/adminRegistServlet")
public class adminRegistServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("html/text;charset=utf-8");
        //1.获取数据
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        //2.判断用户名不能为空
        if (name==null||"".equals(name)){
            System.out.println("用户名不能为空!");
            String s = "用户名不能为空";
            response.getWriter().write(s);
        }
        //连接数据库,插入数据
        Connection conn = null;
        PreparedStatement psta = null;
        String sql = "insert into admin value (?,?)";

        try {
            conn = JDBCUtil.getConnection();
            psta = conn.prepareStatement(sql);
            psta.setString(1,name);
            psta.setString(2,password);
            psta.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psta,conn);
        }
        response.sendRedirect("adminlogin.html");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request,response);
    }
}

4.1.6管理员登陆后的显示的主界面

4.1.7管理员添加商品的方法

import utils.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(name = "adminaddbooksServlet",urlPatterns = "/adminaddbooksServlet")
public class adminaddbooksServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("html/text;charset=utf-8");
        //1.获取数据
        String name = request.getParameter("name");
        String writer = request.getParameter("writer");
        String type=request.getParameter("type");
        String id=request.getParameter("id");
        int number= Integer.parseInt(request.getParameter("number"));
        int price= Integer.parseInt(request.getParameter("price"));
        //2.判断用户名不能为空
        /*if (name==null||"".equals(name)&&writer==null||"".equals(writer)&&type==null||"".equals(type)&&id==null||"".equals(id)&&number==0||"".equals(price)&&writer==null||"".equals(price)){
            String s = "书籍信息要写完整";
            response.getWriter().write(s);
            response.sendRedirect("addbooks.html");
        }*/
        //连接数据库,插入数据
        Connection conn = null;
        PreparedStatement psta = null;
        String sql = "insert into book value (?,?,?,?,?,?)";

        try {
            conn = JDBCUtil.getConnection();
            psta = conn.prepareStatement(sql);
            psta.setString(1,name);
            psta.setString(2,writer);
            psta.setString(3,type);
            psta.setString(4,id);
            psta.setInt(5,number);
            psta.setInt(6,price);
            psta.execute();
            /*int i = psta.executeUpdate(sql);
            if(i>0){
                //request.getRequestDispatcher("adminlogin.html").forward(request,response);
                response.sendRedirect("adminnavcation.jsp");
            }else {
                System.out.println("插入失败!");
            }*/
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psta,conn);
        }
        response.sendRedirect("adminnavcation.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request,response);
    }
}

4.1.7 管理员删除商品的方法

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false"  %>
<%@ page import="java.util.List" %>
<%@ page import="bean.*" %>
<%@ page import="java.io.PrintWriter" %>
<html>
<head>
    <title>管理员删除图书页面</title>
</head>
<body>
<%
    //获取得到传递过来的id
    String id = request.getParameter("bid");
    BookDao dao=new BookDao();
    dao.deletebook(id);
    response.sendRedirect("adminnavcation.jsp");
%>
</body>
</html>

4.1.8管理员修改图书单价的方法

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false"  %>
<%@ page import="java.util.List" %>
<%@ page import="bean.*" %>
<%@ page import="java.io.PrintWriter" %>
<html>
<head>
    <title>修改图书单价页面</title>

</head>
<body>
<%
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    //获取得到传递过来的id
    String bookname=request.getParameter("name");
    int price= Integer.parseInt(request.getParameter("price"));
    BookDao dao=new BookDao();
    dao.updateprice(bookname,price);
    response.sendRedirect("adminnavcation.jsp");
%>
</body>
</html>

4.1.9管理员修改图书库存的方法

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false"  %>
<%@ page import="java.util.List" %>
<%@ page import="bean.*" %>
<%@ page import="java.io.PrintWriter" %>
<html>
<head>
    <title>修改图书数量页面</title>
</head>
<body>
<%
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    //获取得到传递过来的id
    String bookname=request.getParameter("name");
    int number= Integer.parseInt(request.getParameter("number"));
    BookDao dao=new BookDao();
    dao.updatenumber(bookname,number);
    response.sendRedirect("adminnavcation.jsp");
%>
</body>
</html>

4.1.10管理员查看所有用户订单的方法

<%@ page import="java.util.List" %>
<%@ page import="bean.*" %>
<%@ page import="bean.ShoppingCar" %>
<%@ page import="java.util.ArrayList" %><%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2019/11/17
  Time: 16:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>管理员查看订单</title>
</head>
<link rel="stylesheet" type="text/css" href="showallbooks.css">
<body style="margin: 0 auto; padding: 0; background-repeat: no-repeat">
<%

    ShoppingcarDao dao=new ShoppingcarDaoImpl();
    List<ShoppingCar> clist=dao.Queryallorderlist();
    pageContext.setAttribute("clist",clist);

%>
<c:if test="${empty(clist)}">
    <h1>暂无订单!</h1>
</c:if>

<%--如果购物车有购物项,就应该把购物项的信息显示给用户--%>
<c:if test="${!empty(clist)}">
<table id="tb">

     <tr>
     <td>买家</td>

     <td>书籍编号</td>

     <td>书名</td>

     <td>单价</td>

     <td>数量</td>

     <td>小计</td>

     </tr>

     <c:forEach var="clist" items="${clist}" varStatus="status">

     <tr>
     <td>${clist.username}</td>

     <td>${clist.bookid}</td>

     <td>${clist.bookname}</td>

     <td>${clist.bookprice}</td>

    <td>${clist.booknumber}</td>

    <td>${clist.littleprice}</td>
    </tr>
     </c:forEach>
    </c:if>
</table>
</body>
</html>

4.2用户功能实现

4.2.1用户类

4.2.2用户类dao接口

4.2.3用户类dao接口的实现方法(操作数据库)

package bean;

import utils.JDBCUtil;

import java.sql.*;

public class UserDaoImpl implements UserDao {

    @Override
    public void adduser(User u) {
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = "insert into user value (?,?,?)";
            conn = JDBCUtil.getConnection();
            psql=conn.prepareStatement(sql);
            psql.setString(1,u.getName());
            psql.setString(2,u.getPassword());
            psql.setString(3,u.getAddr());
            int i = psql.executeUpdate();
            if(i>0){
                System.out.println("插入成功!");
            }else {
                System.out.println("插入失败!");
            }
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }

    @Override
    public User queryuser(String username) {

        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        User u=new User();

        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from user where name ='" + username + "'";
            rs=statement.executeQuery(sql);
            while(rs.next()){

                u.setName(rs.getString("name"));
                u.setPassword(rs.getString("password"));
            }
            rs.close();
            conn.close();
            return u;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(statement, conn);
        }
        return u;
    }
    public void updatepassword(String name,String password){
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql=conn.prepareStatement("update user set password=? where name='" + name + "'");
            psql.setString(1,password);
            psql.execute();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }

    public void updateaddr(String name,String addr){
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql=conn.prepareStatement("update user set atm.user.address=? where name='" + name + "'");
            psql.setString(1,addr);
            psql.execute();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }
}

4.2.4用户登录页面

4.2.5用户登录的service方法

import bean.User;
import bean.UserDaoImpl;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@javax.servlet.annotation.WebServlet(name = "loginServlet",urlPatterns="/loginServlet")
public class loginServlet extends javax.servlet.http.HttpServlet {

    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        //设置编码和响应类型
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session =request.getSession(true);
        //         1.获得用户名和密码
        //       2.验证用户名和密码是否正确 "zhou" "123456"
        String username=request.getParameter("userName");
        String password=request.getParameter("userPasswd");
        //获得响应的输出流
        PrintWriter pw=response.getWriter();
        UserDaoImpl dao =new UserDaoImpl();
        String name=dao.queryuser(username).getName();
        String passwd=dao.queryuser(username).getPassword();
        if(username.equals(name)&&password.equals(passwd)){
            session.setAttribute("user",username);
            request.getRequestDispatcher("/books.jsp").forward(request,response);
        }else {
            //验证失败
            pw.println("<font color='green'><h2>登录失败</h2></font>");
        }
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
       this.doPost(request,response);
    }
}

4.2.5 用户注册实现的service方法

import utils.JDBCUtil;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
@WebServlet(name = "RegistServlet",urlPatterns = "/RegistServlet")
public class RegistServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("html/text;charset=utf-8");
        //1.获取数据
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String addr = request.getParameter("addr");

        //2.判断用户名不能为空
        if (name==null||"".equals(name)){
            System.out.println("用户名不能为空!");
            String s = "用户名不能为空";
            response.getWriter().write(s);
        }
        //连接数据库,插入数据
        Connection conn = null;
        PreparedStatement psta = null;
        String sql = "insert into user value (?,?,?)";

        try {
            conn = JDBCUtil.getConnection();
            psta = conn.prepareStatement(sql);
            psta.setString(1,name);
            psta.setString(2,password);
            psta.setString(3,addr);
            int i = psta.executeUpdate();
            if(i>0){
                response.sendRedirect("userlogin.html");
            }else {
                System.out.println("插入失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psta,conn);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

4.2.6用户登陆后的显示的主界面

4.2.7用户修改密码的方法

4.2.8用户修改收货地址的方法

4.2.9用户把图书加入购物车的方法

4.2.10用户把图书从购物车中删除的方法

4.2.11用户购物车结算的方法

4.2.12用户查看本用户订单的方法

4.3购物车类

4.3.1购物车类

4.3.2购物车类dao接口

4.3.3购物车类dao接口的实现方法(操作数据库)

package bean;

import utils.JDBCUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ShoppingcarDaoImpl implements ShoppingcarDao{

    public void DeleteBook(String id){
        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "delete  from shoppingcar where bookid="+id;
            statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(statement, conn);
        }
    }
    public Book querybook(String id){
        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        Book b=new Book();
        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from atm.book where bID="+id;
            rs=statement.executeQuery(sql);
            while(rs.next()){

                ShoppingCar s=new ShoppingCar();
                b.setName(rs.getString(1));
                b.setAuthor(rs.getString(2));
                b.setType(rs.getString(3));
                b.setId(rs.getString(4));
                b.setNumber(rs.getInt(5));
                b.setPrice(rs.getInt(6));
            }
            rs.close();
            conn.close();
            return b;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(statement, conn);
        }
        return b;
    }
    public void inserts(Book b,String username,int number){
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql= conn.prepareStatement("insert shoppingcar(username, bookid, bookname, bookprice, booknumber)"+"values(?,?,?,?,?)");
            psql.setString(1,username);
            psql.setString(2, b.getId());
            psql.setString(3, b.getName());
            psql.setInt(4,b.getPrice());
            psql.setInt(5,number);
            psql.execute();
            conn.close();
        }
        catch (SQLException e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }
    public void update(Book b,String username,int number){
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        List<ShoppingCar> list=new ArrayList<ShoppingCar>();
        try {
            conn = JDBCUtil.getConnection();
            psql= conn.prepareStatement("update shoppingcar set booknumber = ? where bookid=? and username in (select username from user where username='" + username + "')");
            //psql= conn.prepareStatement("update shoppingcar set booknumber = ? where bookid=?");
            //psql= conn.prepareStatement("update shoppingcar set booknumber = ? where (bookid=? and username='\" + username + \"')");
            //psql= conn.prepareStatement("update shoppingcar set booknumber = ? where bookid=? and username='\" + username + \"'");
            //psql= conn.prepareStatement("update shoppingcar set username,bookid,bookname,bookprice,booknumber=? where username=?");
            psql.setInt(1,number);
            psql.setString(2,b.getId());
            psql.execute();
            conn.close();
            } catch (SQLException e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }

    public ShoppingCar Queryone1(String username, String id) {
        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        ShoppingCar s=new ShoppingCar();
        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from shoppingcar where  bookid="+id+" and username in (select username from  shoppingcar where username='" + username + "')";
            rs=statement.executeQuery(sql);
            {
                while(rs.next()){
                    s.setUsername(rs.getString(1));
                    s.setBookid(rs.getString(2));
                    s.setBookname(rs.getString(3));
                    s.setBookprice(rs.getInt(4));
                    s.setBooknumber(rs.getInt(5));
                }
            }
            rs.close();
            conn.close();
            return s;
        } catch (SQLException e){
            e.printStackTrace();
        }
        finally {
            JDBCUtil.close(statement, conn);
        }
        return s;
    }
    public int Queryone(String username, String id){
        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        int number=1;
        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from shoppingcar where  username='" + username + "'" ;
            rs=statement.executeQuery(sql);
            {
                while(rs.next()){
                    if(rs.getString(2).equals(id))
                    number+=(rs.getInt(5));
                }
            }
            rs.close();
            conn.close();
        } catch (SQLException e){
            e.printStackTrace();
        }
        finally {
            JDBCUtil.close(statement, conn);
        }
        return number;
    }

    public int Queryone2(String username, String id){
        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        int number=0;
        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from shoppingcar where  username='" + username + "'" ;
            rs=statement.executeQuery(sql);
            {
                while(rs.next()){
                    if(rs.getString(2).equals(id))
                        number=(rs.getInt(5));
                }
            }
            rs.close();
            conn.close();
        } catch (SQLException e){
            e.printStackTrace();
        }
        finally {
            JDBCUtil.close(statement, conn);
        }
        return number;
    }
    public List<ShoppingCar> Queryall(String username){
        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        List<ShoppingCar> list=new ArrayList<ShoppingCar>();
        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from shoppingcar where username='" + username + "'";
            rs=statement.executeQuery(sql);
            while(rs.next()){
                ShoppingCar s=new ShoppingCar();
                s.setUsername(rs.getString(1));
                s.setBookid(rs.getString(2));
                s.setBookname(rs.getString(3));
                s.setBookprice(rs.getInt(4));
                s.setBooknumber(rs.getInt(5));
                list.add(s);
            }
            rs.close();
            conn.close();
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(statement, conn);
        }
        return list;
    }

    public List<ShoppingCar> Queryallorderlist(){
        //连接数据库
        Connection conn = null;
        Statement statement=null;
        ResultSet rs=null;
        List<ShoppingCar> list=new ArrayList<ShoppingCar>();
        try {
            conn = JDBCUtil.getConnection();
            statement = conn.createStatement();
            String sql = "select * from orderlist";
            rs=statement.executeQuery(sql);
            while(rs.next()){
                ShoppingCar s=new ShoppingCar();
                s.setUsername(rs.getString(1));

                System.out.println(s.getUsername());//调试

                s.setBookid(rs.getString(2));
                s.setBookname(rs.getString(3));
                s.setBookprice(rs.getDouble(4));
                s.setBooknumber(rs.getInt(5));
                list.add(s);
            }
            rs.close();
            conn.close();
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtil.close(statement, conn);
        }
        return list;
    }
    public void updatenumber(String id,int number){
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql= conn.prepareStatement("update book set bNumber = ? where bID=?");
            psql.setInt(1,number);
            psql.setString(2,id);
            psql.execute();
            conn.close();
        } catch (SQLException e){
            e.printStackTrace();
        }
        finally {
            JDBCUtil.close(psql, conn);
        }
    }
    public void drop(String username){
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql= conn.prepareStatement("delete from shoppingcar where username=?");
            psql.setString(1,username);
            psql.execute();
            conn.close();
        } catch (SQLException e){
            e.printStackTrace();
        }        finally {
            JDBCUtil.close(psql, conn);
        }
    }
    //单个结算后把记录写入订单表
    public void orderlist1(ShoppingCar s){
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql= conn.prepareStatement("insert orderlist(customer, bookId, bookName, bookPrice, bookNumber)"+"values(?,?,?,?,?)");
                psql.setString(1,s.getUsername());
                psql.setString(2, s.getBookid());
                psql.setString(3, s.getBookname());
                psql.setDouble(4,s.getBookprice());
                psql.setInt(5,s.getBooknumber());
                psql.execute();
            conn.close();
        } catch (SQLException e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }
    //结算后把购物车记录写入订单表
    public void orderlist(List<ShoppingCar> list){
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql= conn.prepareStatement("insert orderlist(customer, bookId, bookName, bookPrice, bookNumber)"+"values(?,?,?,?,?)");
            for(ShoppingCar s:list){
                psql.setString(1,s.getUsername());
                psql.setString(2, s.getBookid());
                psql.setString(3, s.getBookname());
                psql.setDouble(4,s.getBookprice());
                psql.setInt(5,s.getBooknumber());
                psql.execute();
            }
            conn.close();
        } catch (SQLException e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(psql, conn);
        }
    }
   public List<ShoppingCar> showuserorderlist(String username){
       //连接数据库
       Connection conn = null;
       Statement statement=null;
       ResultSet rs=null;
       List<ShoppingCar> list=new ArrayList<ShoppingCar>();
       try {
           conn = JDBCUtil.getConnection();
           statement = conn.createStatement();
           String sql = "select * from orderlist where customer='" + username + "'";
           rs=statement.executeQuery(sql);
           while(rs.next()){
               ShoppingCar s=new ShoppingCar();
               s.setBookid(rs.getString(2));
               s.setBookname(rs.getString(3));
               s.setBookprice(rs.getInt(4));
               s.setBooknumber(rs.getInt(5));
               list.add(s);
           }
           rs.close();
           conn.close();
           return list;
       } catch (SQLException e) {
           e.printStackTrace();
       }finally {
           JDBCUtil.close(statement, conn);
       }
       return list;
   }

    public void deleteonebook(String username,String id){
        //连接数据库
        Connection conn = null;
        PreparedStatement psql=null;
        ResultSet rs=null;
        try {
            conn = JDBCUtil.getConnection();
            psql= conn.prepareStatement("delete from shoppingcar where username=? and bookid in (select bookid from shoppingcar where bookid=?)");
            psql.setString(1,username);
            psql.setString(2,id);
            psql.execute();
            conn.close();
        } catch (SQLException e){
            e.printStackTrace();
        }        finally {
            JDBCUtil.close(psql, conn);
        }
    }
}

4.3.4购物车显示页面

5.3图书类及方法

5.3.1图书类

5.3.2图书类dao实现方法

5.3.3显示所有图书的方法

JDBCUtil工具类

package utils;
import javax.sql.DataSource;
import java.sql.*;
import bean.User;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.util.Properties;
public class JDBCUtil {
    private  static DataSource ds ;
    //加载配置文件,创建数据库连接池
    static{

        try {
            Properties pro = new Properties();
            pro.load(JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接池对象
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    //释放资源
    public static void close(Statement sttm, Connection conn, ResultSet rs){
        if(sttm!=null){
            try {
                sttm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Statement sttm, Connection conn){
        close(sttm,conn,null);
    }
    public static DataSource getDs(){
        return ds;
    }

}

sql文件

/*
Navicat MySQL Data Transfer

Source Server         : DESKTOP-7UO4BFR
Source Server Version : 50725
Source Host           : localhost:3306
Source Database       : atm

Target Server Type    : MYSQL
Target Server Version : 50725
File Encoding         : 65001

Date: 2020-12-09 13:34:02
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `account`
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `UserID` varchar(20) NOT NULL,
  `UserName` varchar(15) DEFAULT NULL,
  `money` int(11) DEFAULT NULL,
  PRIMARY KEY (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES ('1815925066', '周文豪', '1400');
INSERT INTO `account` VALUES ('1815925067', '闫守建', '1400');

-- ----------------------------
-- Table structure for `admin`
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
  `name` varchar(20) NOT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of admin
-- ----------------------------
INSERT INTO `admin` VALUES ('俞敏洪', '123456');
INSERT INTO `admin` VALUES ('李嘉诚', '123456');
INSERT INTO `admin` VALUES ('王健林', '123456');
INSERT INTO `admin` VALUES ('马云', '123456');

-- ----------------------------
-- Table structure for `book`
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
  `bName` varchar(20) NOT NULL,
  `bWtiter` varchar(15) DEFAULT NULL,
  `bType` varchar(15) DEFAULT NULL,
  `bID` varchar(15) DEFAULT NULL,
  `bNumber` int(11) DEFAULT NULL,
  `bPrice` int(11) DEFAULT NULL,
  PRIMARY KEY (`bName`),
  KEY `bID` (`bID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES ('三体', '刘慈欣', '科幻小说', '004', '29', '55');
INSERT INTO `book` VALUES ('三国演义', '罗贯中', '四大名著', '001', '21', '35');
INSERT INTO `book` VALUES ('假面山庄', '东野圭吾', '外国小说', '005', '25', '88');
INSERT INTO `book` VALUES ('昆虫记', '法布尔', '文学', '033', '40', '40');
INSERT INTO `book` VALUES ('比索寓言', '比索', '寓言故事', '008', '2', '20');
INSERT INTO `book` VALUES ('活着', '余华', '现实主义小说', '006', '6', '36');
INSERT INTO `book` VALUES ('西游记', '吴承恩', '四大名著', '002', '23', '30');
INSERT INTO `book` VALUES ('钢铁是怎样炼成的', '尼古拉·奥斯特洛夫斯基', '外国名著', '003', '34', '56');

-- ----------------------------
-- Table structure for `orderlist`
-- ----------------------------
DROP TABLE IF EXISTS `orderlist`;
CREATE TABLE `orderlist` (
  `customer` varchar(20) DEFAULT NULL,
  `bookID` varchar(20) DEFAULT NULL,
  `bookName` varchar(20) DEFAULT NULL,
  `bookPrice` double(20,0) DEFAULT NULL,
  `bookNumber` int(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of orderlist
-- ----------------------------
INSERT INTO `orderlist` VALUES ('Tom', '003', '钢铁是怎样炼成的', '56', '1');
INSERT INTO `orderlist` VALUES ('Tom', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('Tom', '005', '假面山庄', '88', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '005', '假面山庄', '88', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '005', '假面山庄', '88', '3');
INSERT INTO `orderlist` VALUES ('周文豪', '006', '活着', '36', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '003', '钢铁是怎样炼成的', '56', '2');
INSERT INTO `orderlist` VALUES ('周文豪', '001', '三国演义', '35', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('张世强', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('张世强', '001', '三国演义', '35', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '001', '三国演义', '35', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '006', '活着', '36', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '006', '活着', '36', '1');
INSERT INTO `orderlist` VALUES ('周文豪', '002', '西游记', '30', '2');
INSERT INTO `orderlist` VALUES ('闫守建', '007', '安徒生童话', '15', '1');
INSERT INTO `orderlist` VALUES ('闫守建', '004', '三体', '55', '1');
INSERT INTO `orderlist` VALUES ('闫守建', '003', '钢铁是怎样炼成的', '56', '1');

-- ----------------------------
-- Table structure for `shoppingcar`
-- ----------------------------
DROP TABLE IF EXISTS `shoppingcar`;
CREATE TABLE `shoppingcar` (
  `username` varchar(20) DEFAULT NULL,
  `bookid` varchar(20) DEFAULT NULL,
  `bookname` varchar(20) DEFAULT NULL,
  `bookprice` int(20) DEFAULT NULL,
  `booknumber` int(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of shoppingcar
-- ----------------------------

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `name` varchar(15) NOT NULL,
  `password` varchar(20) DEFAULT NULL,
  `address` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('CATs', '123456', '奥术大师大奥所');
INSERT INTO `user` VALUES ('James', '123456', '奥术大师大奥所');
INSERT INTO `user` VALUES ('Tom', '123456', '南洋理工学院12号公寓205');
INSERT INTO `user` VALUES ('zhou', '123456', '南阳理工学院12#201');
INSERT INTO `user` VALUES ('侯明明', '123456', '南阳理工学院12#201');
INSERT INTO `user` VALUES ('周五', '123456', '是的撒多所多所多所多所多、');
INSERT INTO `user` VALUES ('周文豪', '123456', '南阳理工学院');
INSERT INTO `user` VALUES ('张世强', '123456', '南洋理工学院12号公寓201');
INSERT INTO `user` VALUES ('曹瑾', '123456', '南阳理工学院12#215');
INSERT INTO `user` VALUES ('朱命豪', '666666', '南阳理工学院');
INSERT INTO `user` VALUES ('王康', '123456', '河南大学');
INSERT INTO `user` VALUES ('米军臣', '123456', '南阳理工学院12#212');
INSERT INTO `user` VALUES ('胡广涛', '123456', '南阳理工学院12#218');
INSERT INTO `user` VALUES ('薛之谦', '123456', '南阳理工学院12#215');
INSERT INTO `user` VALUES ('邝凯兴', '123456', '南阳理工学院12#331');
INSERT INTO `user` VALUES ('闫守建', '123456', '南洋理工学院12号公寓201');
INSERT INTO `user` VALUES ('靳凌霄', '123456', '南阳理工学院12#201');

-- ----------------------------
-- Table structure for `user2`
-- ----------------------------
DROP TABLE IF EXISTS `user2`;
CREATE TABLE `user2` (
  `id` varchar(11) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `address` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of user2
-- ----------------------------
INSERT INTO `user2` VALUES ('1815925061', 'sdsdssdsd', '123456', '南阳理工');
INSERT INTO `user2` VALUES ('1815925066', '周文豪', '123456', '南阳理工');
INSERT INTO `user2` VALUES ('1815925110', '闫守建', '123456', '南阳理工');
INSERT INTO `user2` VALUES ('1815925116', '周六', '123456', '南阳理工');
INSERT INTO `user2` VALUES ('1815925118', '周五', '123456', '南阳理工');
INSERT INTO `user2` VALUES ('1815925167', '侯明明', '123456', '南阳理工');

-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `UserID` varchar(20) NOT NULL,
  `Username` varchar(15) DEFAULT NULL,
  `UserPassword` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`UserID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1815925066', '周文豪', '123456');
INSERT INTO `users` VALUES ('1815925067', '闫守建', '123456');

数据库连接池

Druid.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///atm?characterEncoding=utf8
username=root
password=zwh19991219
initialSize=5
maxActive=10
maxWait=3000
maxIdle=8
minIdle=3

需要用到的jar包

需要项目源码的可以去我个人gitHub下载(不帮忙解决问题,有问题自己解决):GitHub - zhouwenhao123456/bookStore: javaWeb开发网上书城项目

注意:
项目没有任何问题,出现404和报红是自己没配好,
因不会配置导致项目无法正常运行的,本人概不负责!

当然,如果你觉得我的项目对你有帮助的话,

看个人心情适当打赏几块钱,请博主喝瓶可乐,hhhh~

开发软件IDEA,如果是ecplise的读者,需要上网查找IDEA转ecplise的方法

MYSQL5.6 和 MYSQL 8.0版本的都有(区别就在于一个配置文件)

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐