基于JSP和Servlet的简单自动贩卖机购物(软件测试作业)

1、目标

编写一个基于java用于软件测试的商品系统(软件测试就测试吧,为什么还要我写个程序)。

数据库基于MySQL,CRUD操作通过JDBC实现的。

使用到的工具有Idea,Navicat for MySQL。

2、需求和可行性分析

JSP实现网页的动态数据显示,Servlet用来处理数据和请求响应。用到了一些MVC的概念,把实体类、控制、数据库操作拆开来调用实现解耦合。

增删改查用到了JDBC,java提供的一套用来操作数据库的api。增删改查要写简单的SQL语句,其实我感觉不会SQL语句也可以,数据库可视化管理工具挺好用的。

前端网页的显示有三大块,登录界面、后台数据管理、商品信息展示。实现的功能有根据权限进行登录、购物车进行购物、后台数据管理。

3、功能实现

1、登录功能的实现

登录的功能是让Servlet接收到前端提交的数据后,根据输入的账号和密码在数据库中进行检索。如果存在Servlet就会将页面跳转到后台数据管理界面,否则就让前端显示登录失败的错误信息。

创建一个登录用的JSP页面

<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2023/6/20
  Time: 20:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String str;
    if (session.getAttribute("info") == null) {
        str = "";
    } else {
        str = (String) session.getAttribute("info");
    }
%>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        html {
            height: 100%;
        }

        body {
            height: 100%;
        }

        .container {
            height: 100%;
            background-image: linear-gradient(110deg, #082516, #041538);
        }

        .login-wrapper {
            background-color: #fbf1f1;
            width: 400px;
            height: 500px;
            border-radius: 50px;
            padding: 0 50px;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

        .header {
            font-size: 60px;
            font-weight: 900;
            text-align: center;
            line-height: 120px;
        }

        .input-item {
            display: block;
            width: 100%;
            margin-bottom: 20px;
            border: 0;
            padding: 10px;
            border-bottom: 1px solid rgb(128, 125, 125);
            font-size: 15px;
            outline: none;
        }

        .input-item::placeholder {
            text-transform: uppercase;
        }

        .btn {
            text-align: center;
            padding: 10px;
            width: 100%;
            margin-top: 40px;
            background-image: linear-gradient(to right, #041538, #082516);
            color: #fff;

        }

        .msg {
            text-align: center;
            line-height: 88px;
        }

        a {
            text-decoration-line: none;
            color: #abc1ee;
        }
    </style>
</head>
<body>
<form action="login" method="get">
    <div class="container">
        <div class="login-wrapper">
            <div class="header">Login</div>
            <div class="form-wrapper">
                <input type="text" name="userid" placeholder="账户名" class="input-item">
                <input type="password" name="password" placeholder="密码" class="input-item">
                <div class="btn"><input type="submit" value="点击登录" style="border:0px;background:none;color:#fff"></div>
                <%--            //设置一个内嵌CSS样式给input提交标签--%>

                <div class="btn"><input type="button" value="返回商品信息浏览页" style="border:0px;background:none;color:#fff" onclick="location='showinfoTwo.jsp'"></div>
                <div class="btn"><input type="button" value="忘记密码" style="border:0px;background:none;color:#fff" onclick="location='updatePassWord.jsp'"></div>

                <p style="color: red"><%=str%>
                </p>
            </div>
            <div class="msg">


            </div>
        </div>
    </div>
</form>
</body>
</html>
>

创建一个dao包,并创建一个类用来进行数据库操作。

这个类完成后可能有一些问题要注意下。是否导入对应于JDK版本的数据库连接驱动包。数据库的地址,账号,密码是否有问题。电脑上的MySql数据库是否处在正常工作状态。

package com.liao.dao;

import com.liao.entity.Product;
import com.liao.entity.User;

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

public class Db {


    public void add(Product product) {    //添加商品信息

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        Product p = null;
        List<Product> products = new ArrayList<>();
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products", "root", "root");
            //获取预处理块
            preparedStatement = connection.prepareStatement("insert into product(name,price,number)values (?,?,?)"); //

            preparedStatement.setString(1, product.getName());
            preparedStatement.setInt(2, product.getPrice());
            preparedStatement.setInt(3, product.getNumber());
            preparedStatement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }   //添加商品信息


    public void delete(String name) {   //删除商品信息

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        Product p = null;
        List<Product> products = new ArrayList<>();
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products", "root", "root");
            //获取预处理块
            preparedStatement = connection.prepareStatement("delete from product where name=?"); //删除user表中name为?的信息

            preparedStatement.setString(1, name);//设置第一个?的值 然后进行删除操作
            preparedStatement.executeUpdate();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }     //删除商品信息

    public void update(Product product) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Product p = null;

        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products", "root", "root");
            System.out.println(connection);
            //获取预处理块
            preparedStatement = connection.prepareStatement("UPDATE product SET number = ? WHERE name = ? ");

            preparedStatement.setInt(1, product.getNumber());
            preparedStatement.setString(2, product.getName());

            preparedStatement.executeUpdate();



        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();

                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }//更新商品信息


    public List<Product> findAll() {   //获取所有商品信息
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Product p = null;
        List<Product> products = new ArrayList<>();
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products?useUnicode=true&characterEncoding=utf8", "root", "root");
            System.out.println(connection);
            //获取预处理块
            preparedStatement = connection.prepareStatement("select * from  product");


            resultSet = preparedStatement.executeQuery();
            //从resultSet从获取获取结果值
            while (resultSet.next()) {
                System.out.println("对从数据库获取的数据进行装载");
                p = new Product(resultSet.getString("name"), resultSet.getInt("number"), resultSet.getInt("price"));
                products.add(p);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                resultSet.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return products;
    }         //查询所有商品信息

    public Product findOne(String name) {   //根据商品信息查询商品

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        Product p = null;

        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products", "root", "root");
            System.out.println(connection);
            //获取预处理块
            preparedStatement = connection.prepareStatement("select * from  product where name=?");

            preparedStatement.setString(1, name);
            resultSet = preparedStatement.executeQuery();

            //从resultSet从获取获取结果值
            while (resultSet.next()) {
                System.out.println("对从数据库获取的数据进行装载");
                p = new Product(resultSet.getString("name"), resultSet.getInt("number"), resultSet.getInt("price"));

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                resultSet.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return p;
    }    //查询一个商品信息


    public User findUser(User user) {   //获取用户信息
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User u = null;


        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products", "root", "root");
            //获取预处理块
            preparedStatement = connection.prepareStatement("select * from  user where id=? and password=?");
            preparedStatement.setInt(1,user.getUserid());
            preparedStatement.setInt(2,user.getPassword());


            resultSet = preparedStatement.executeQuery();
            System.out.println("==================================================");
            while (resultSet.next()) {
                System.out.println("对从数据库获取的数据进行装载");  //如果数据库中未找到匹配的账户和密码,数据库将返回一个空结果,servlet中如果判空则显示登录失败
                u = new User(resultSet.getInt("power"), resultSet.getInt("id"), resultSet.getInt("password"));
                System.out.println(resultSet.getInt("power"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                resultSet.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return u;
    }          //查询用户信息

    public User findUser(int id,int power) {   //根据账号和手机号获取用户信息
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User u = null;


        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products", "root", "root");
            //获取预处理块
            preparedStatement = connection.prepareStatement("select * from  user where id=? and power=?");
            preparedStatement.setInt(1,id);
            preparedStatement.setInt(2,power);


            resultSet = preparedStatement.executeQuery();
            System.out.println("==================================================");
            while (resultSet.next()) {
                System.out.println("对从数据库获取的数据进行装载");  //如果数据库中未找到匹配的账户和密码,数据库将返回一个空结果,servlet中如果判空则显示登录失败
                u = new User(resultSet.getInt("power"), resultSet.getInt("id"), resultSet.getInt("password"));
                System.out.println(resultSet.getInt("power"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();
                resultSet.close();
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return u;
    }          //根据手机号和账号获取用户信息

    public void  update(User user){

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        Product p = null;

        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");

            //获取链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/products", "root", "root");
            System.out.println(connection);
            //获取预处理块
            preparedStatement = connection.prepareStatement("UPDATE user SET password = ? WHERE id = ? ");

            preparedStatement.setInt(1, user.getPassword());
            preparedStatement.setInt(2, user.getUserid());

            preparedStatement.executeUpdate();



        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                preparedStatement.close();

                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }


}

编写一个Servlet用来进行控制

package com.liao.control;

import com.liao.dao.Db;
import com.liao.entity.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "Servlet_Login", value = "/Servlet_Login")
public class Servlet_Login extends HttpServlet {

    Db dbControl = new Db();
    User userControl = null;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /**
         2023.6.20: 今日完成数据库商品对象的操作方法,并开始编写登录界面的servlet和jsp页面
         在该登录方法中要实现普通用户和管理员操作的区别,具体实现方法是给用户对象设置一个权限值,当值为1为管理员,为0则为普通用户
         */


        /**
         2023.6.21:
         今日开始编写登录逻辑和登录界面
         */




        User user = new User(Integer.parseInt(request.getParameter("userid")), Integer.parseInt(request.getParameter("password")));//创建一个前端传递的用户对象给数据库进行查找
        userControl = dbControl.findUser(user);//服务器内部的用户对象
        if (userControl == null) {

            request.setAttribute("info", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("infoMange.jsp").forward(request, response);
        }

    }
}

我草,好累,不想写了。直接放代码吧,我懒狗。

后记

这是很久以前我写过的一个作业,当时真是啥也不会感觉。自己在B站学了一个星期的JSP后把这个简单的系统实现出来了。希望这个小系统能给后来的同学提供一些参考。