JavaWeb综合项目——快递e栈(后台部分)(二)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: JavaWeb综合项目——快递e栈(后台部分)(二)

6 管理员登录前后端交互


6.1 登录


前端页面login.html:


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="assets/css/layui.css">
    <link rel="stylesheet" href="assets/css/login.css">
    <link rel="icon" href="/favicon.ico">
    <title>快递e栈管理后台</title>
</head>
<body class="login-wrap">
    <div class="login-container">
       <h3>快递e栈后台管理</h3>
        <form class="login-form" action="index.html">
            <div class="input-group">
                <input type="text" id="username" class="input-field">
                <label for="username" class="input-label">
                    <span class="label-title">用户名</span>
                </label>
            </div>
            <div class="input-group">
                <input type="password" id="password" class="input-field">
                <label for="password" class="input-label">
                    <span class="label-title">密码</span>
                </label>
            </div>
            <button type="button" class="login-button">登录<i class="ai ai-enter"></i></button>
        </form>
    </div>
</body>
<script src="assets/layui.js"></script>
<script src="js/index.js" data-main="login"></script>
<script src="js/login.js" data-main="login"></script>
<script src="../qrcode/jquery2.1.4.js"></script>
<script src="../layer/layer.js"></script>
<script>
    $(function () {
        $(".login-button").click(function () {
            var username = $("#username").val();
            var password = $("#password").val();
            if(username == null || password == null || username == "" || password == ""){
                alert("用户名或密码不能为空");
           }else{
                // 先转圈(使用layer弹出load,提示加载中)
                var windowId = layer.load();
                // ajax与服务器交互
                $.post("login.do", {username:username, password:password}, function (data) {
                    // 关闭load窗口
                    layer.close(windowId);
                    // 将服务器回复的结果进行显示
                    layer.msg(data.result);
                    if (data.status == 0){
                        // 跳转到主页
                        location.assign("index.html");
                    }
                }, "JSON");
            }
        });
    })
</script>
</html>


编写管理员登录的controller:


package com.wangjiawei.controller;
import com.wangjiawei.bean.Message;
import com.wangjiawei.mvc.ResponseBody;
import com.wangjiawei.service.AdminService;
import com.wangjiawei.util.JSONUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/2 10:28
 * 4
 */
public class AdminController {
    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean result = AdminService.login(username, password);
        // 准备不同的返回数据
        Message msg = null;
        if (result){
            // {status:0, result:"登录成功"}
            msg = new Message(0, "登录成功");
            // 登录时间和ip的更新
            Date date = new Date();
            String ip = request.getRemoteAddr();
            AdminService.updateLoginTimeAndIp(username, date, ip);
        }else {
            // {status:-1, result:"登录失败"}
            msg = new Message(-1, "登录失败");
        }
        String json = JSONUtil.toJSON(msg);
        return json;
    }
}


为了不显示乱码,定义过滤器设置编码:


package com.wangjiawei.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/2 10:50
 * 4
 */
@WebFilter("*.do")
public class CharSetFilter implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        chain.doFilter(req, resp);
    }
    public void init(FilterConfig config) throws ServletException {
    }
}

6.2 显示当前用户姓名(以主页面为例)


AdminController中添加获取姓名方法:



         


index.html部分:


$.post("/admin/getName.do",{},function (data) {
    // {
    //     "status": 0,
    //     "result": "查询成功",
    //     "data": "admin"
    // }
    $("#adminName").text(data.data);
});


6.3 退出登录(以主页面为例)


AdminController中添加退出登录方法:


@ResponseBody("/admin/logout.do")
public String logout(HttpServletRequest request, HttpServletResponse response){
    HttpSession session = request.getSession();
    session.removeAttribute("adminUserName");
    Message msg = new Message();
    msg.setStatus(0);
    msg.setResult("退出成功");
    String json = JSONUtil.toJSON(msg);
    return json;
}


index.html完整代码:


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="assets/css/layui.css">
    <link rel="stylesheet" href="assets/css/admin.css">
    <link rel="icon" href="/favicon.ico">
    <title>快递e栈管理后台</title>
</head>
<body class="layui-layout-body">
    <div class="layui-layout layui-layout-admin">
        <div class="layui-header custom-header">
            <ul class="layui-nav layui-layout-left">
                <li class="layui-nav-item slide-sidebar" lay-unselect>
                    <a href="javascript:;" class="icon-font"><i class="ai ai-menufold"></i></a>
                </li>
            </ul>
            <ul class="layui-nav layui-layout-right">
                <li class="layui-nav-item">
                    <a><span id="adminName">aaaaaaa</span></a>
                    <dl class="layui-nav-child">
                        <dd><a href="#">帮助中心</a></dd>
                        <dd><a id="logout" href="login.html">退出</a></dd>
                    </dl>
                </li>
            </ul>
        </div>
        <div class="layui-side custom-admin">
            <div class="layui-side-scroll">
                <div class="custom-logo">
                    <img src="assets/images/logo.gif" alt=""/>
                    <h1>快递e栈</h1>
                </div>
                <ul id="Nav" class="layui-nav layui-nav-tree">
                    <li class="layui-nav-item">
                        <a href="javascript:;">
                            <i class="layui-icon">&#xe68e;</i>
                            <em>主页</em>
                        </a>
                        <dl class="layui-nav-child">
                            <dd><a href="views/console.html"><i class="layui-icon">&#xe665;</i> 控制台</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">
                            <i class="layui-icon">&#xe664;</i>
                            <em>快递员管理</em>
                        </a>
                        <dl class="layui-nav-child">
                            <dd><a href="views/courier/list.html"><i class="layui-icon">&#xe60a;</i> 快递员列表</a></dd>
                            <dd><a href="views/courier/add.html"><i class="layui-icon">&#xe654;</i> 快递员录入</a></dd>
                            <dd><a href="views/courier/update.html"><i class="layui-icon">&#xe642;</i> 快递员修改</a></dd>
                            <dd><a href="views/courier/delete.html"><i class="layui-icon">&#xe640;</i> 快递员删除</a></dd>
                        </dl>
                    </li>
                    <li class="layui-nav-item">
                        <a href="javascript:;">
                            <i class="layui-icon">&#xe857;</i>
                            <em>快件管理</em>
                        </a>
                        <dl class="layui-nav-child">
                            <dd><a href="views/express/list.html"><i class="layui-icon">&#xe60a;</i> 快件列表</a></dd>
                            <dd><a href="views/express/add.html"><i class="layui-icon">&#xe654;</i> 快件录入</a></dd>
                            <dd><a href="views/express/update.html"><i class="layui-icon">&#xe642;</i> 快件修改</a></dd>
                            <dd><a href="views/express/delete.html"><i class="layui-icon">&#xe640;</i> 快件删除</a></dd>
                        </dl>
                    </li>
                     <li class="layui-nav-item">
                        <a href="javascript:;">
                            <i class="layui-icon">&#xe770;</i>
                            <em>用户管理</em>
                        </a>
                        <dl class="layui-nav-child">
                            <dd><a href="views/user/list.html"><i class="layui-icon">&#xe60a;</i> 用户列表</a></dd>
                            <dd><a href="views/user/add.html"><i class="layui-icon">&#xe654;</i> 用户增加</a></dd>
                            <dd><a href="views/user/update.html"><i class="layui-icon">&#xe642;</i> 用户修改</a></dd>
                            <dd><a href="views/user/delete.html"><i class="layui-icon">&#xe640;</i> 用户删除</a></dd>
                        </dl>
                    </li>
                </ul>
            </div>
        </div>
        <div class="layui-body">
             <div class="layui-tab app-container" lay-allowClose="true" lay-filter="tabs">
                <ul id="appTabs" class="layui-tab-title custom-tab"></ul>
                <div id="appTabPage" class="layui-tab-content"></div>
            </div>
        </div>
        <div class="layui-footer">
            <p>©2020 <a href="http://www.itdage.com/" target="_blank">王家尉版权声明</a></p>
        </div>
        <div class="mobile-mask"></div>
    </div>
    <script src="assets/layui.js"></script>
    <script src="js/index.js" data-main="home"></script>
    <script src="/qrcode/jquery2.1.4.js"></script>
    <script>
        $(function () {
            $.post("/admin/getName.do",{},function (data) {
                // {
                //     "status": 0,
                //     "result": "查询成功",
                //     "data": "admin"
                // }
                $("#adminName").text(data.data);
            });
            $("#logout").click(function () {
                var windowId = layer.load();
                $.post("/admin/logout.do",{},function (data) {
                    layer.msg(data.result);
                    layer.close(windowId);
                    location.href = "/admin/login.html";
                })
            });
        });
    </script>
</body>
</html>


7 流程与快递表格创建


7.1 编写流程


1.管理员登录


2.快递管理

快递列表

(1)分页查询的列表

新增快递

(1)用户输入内容,后台接收参数,向数据库存储

删除快递

(1)用户输入快递单号查询快递信息

(2)浏览快递信息的最后,可以点击删除按钮,删除快递

修改快递

(1)用户输入快递单号查询到快递信息

(2)浏览(可修改)快递信息的最后,可以点击确认按钮,确认修改快递


3.用户管理

用户列表

新增用户

删除用户

修改用户


4.快递员管理

快递员列表

新增快递员

删除快递员

修改快递员


5.控制台显示


7.2 编写步骤


创建数据库表格

编写DAO

编写service

编写controller

前后端交互

前端发起ajax→DispatcherServlet→Controller→Service→DAO→数据库

前后端交互标准流程:


前端发起ajax

$("按钮选择器").click(function(){
            //1.    先使用layer,弹出load(提示加载中...)
            var windowId = layer.load();
            //2.    ajax与服务器交互
            $.post("服务器地址",参数JSON,function(data){
                //3.    关闭load窗口
                layer.close(windowId);
                //4.    将服务器回复的结果进行显示
                layer.msg(data.result);
            },"JSON");
        });


编写Controller,用于处理ajax的请求

在Controller中调用service处理

处理完毕, 根据service返回的结果,给ajax返回


7.3 数据库创建


7.3.1 快递


CREATE TABLE Express(
  id int PRIMARY KEY auto_increment,
  number VARCHAR(64) UNIQUE,
  username VARCHAR(32),
  userphone VARCHAR(32),
  company VARCHAR(32),
  code VARCHAR(32) UNIQUE,
  intime TIMESTAMP,
  outtime TIMESTAMP,
  status int,
  sysPhone VARCHAR(32)
);


7.3.2 快递员


create table courier(
  id int primary key auto_increment,
  courierName varchar(32),
  courierPhone varchar(32),
  courierIdNumber varchar(32),
  courierPassword varchar(32),
  courierSendNumber int,
  enrollTime TIMESTAMP,
  loginTime TIMESTAMP
);


7.3.3 用户


create table user(
  id int primary key auto_increment,
  userName varchar(32),
  userPhone varchar(32),
  userIdNumber varchar(32),
  userPassword varchar(32),
  enrollTime timestamp,
  loginTime timestamp
);


7.4 bean


7.4.1 快递类.


package com.wangjiawei.bean;
import java.sql.Timestamp;
import java.util.Objects;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/2 18:55
 * 4
 */
public class Express {
    private int id;
    private String number;
    private String username;
    private String userPhone;
    private String company;
    private String code;
    private Timestamp inTime;
    private Timestamp outTime;
    private int status;
    private String sysPhone;
    /* getter setter toString hash 构造函数略 */
}


7.4.2 快递员类


public class Courier {
    private int id;
    private String courierName;
    private String courierPhone;
    private String courierIdNumber;
    private String courierPassword;
    private String courierSendNumber;
    private Timestamp enrollTime;
    private Timestamp loginTime;
    /* getter setter toString hash 构造函数略 */
}


7.4.3 用户类


public class User {
    private int id;
    private String userName;
    private String userPhone;
    private String userIdNumber;
    private String userPassword;
    private Timestamp enrollTime;
    private Timestamp loginTime;
    /* getter setter toString hash 构造函数略 */
}

8 api设计


8.1 console 部分(控制台)


1. 获取控制台所需的快递数据

请求地址:

 express/console.do

参数列表:

 无

返回格式示例:


{
    status:0,
    result:"获取成功",
    data:[
        { // 全部快递
            size:1000, // 总件数
            day:100    // 当日新增
        },{ // 待取件快递
            size:500,  // 待取件数
           day:100    // 今日新增
        }
    ]
}


8.2 快递管理

1. 快件列表(分页)

请求地址:

 express/findAll.do

参数列表:

 1. limit:

   a. 值:0,开启分页(默认)

   b. 值:1,查询所有

 2. offset:

   值:数字,sql语句的起始索引

 3. pageNumber:

   值:数字,表示每页获取的快递数量


2. 根据单号查询快递信息

请求地址:express/findByNumber.do

参数列表:

 1. number:快递单号


3. 根据取件码查询快递信息

请求地址:express/findByCode.do

参数列表:

 1. code:取件码


4. 根据用户的手机号,查询快递信息

请求地址:express/findByUserPhone.do

参数列表:

 1. userPhone:手机号码

 2. status:

   值:0表示查询待取件的快递(默认)

   值:1表示查询已取件的快递

   值:2表示查询用户的所有快递


5. 根据录入人的手机号,查询快递信息(快递员/柜子的历史记录)

请求地址:express/findBySysPhone.do

参数列表:

 1. sysPhone:手机号码


6. 进行快递数量的排序查询(用户表)

请求地址:express/lazyboard.do

参数列表:

 1. type:

   值:0,表示查询总排名

   值:1,表示查询年排名

   值:2,表示查询月排名


7. 快件录入

请求地址:

 express/insert.do

参数列表:

 1. number:快递单号

 2. company:快递公司

 3. username:收件人姓名

 4. phoneNumber:收件人手机号码


8. 修改快递信息

请求地址:express/update.do

参数列表:

 1. id:要修改的快递id

 2. number:新的快递单号

 3. company:新的快递公司

 4. username:新的收货人姓名

 5. userPhone:新的收件人手机号码,(手机号码更新,重新生成取件码,并发送短信)

 6. status:新的快递的状态


9. 根据id删除快递信息

请求地址:express/delete.do

参数列表:

 1. id: 要删除的快递的id


10. 确认取件

请求地址:express/updateStatus.do

参数列表:

 number:要更改状态为已取件的快递单号


9 dao接口编写与具体实现


9.1 快递操作相关的dao


9.1.1 sql语句书写


/**
 * 查询全部快递(总数+新增),待取件快递(总数+新增)
  */
public static final String SQL_CONSOLE = "SELECT " +
        "COUNT(ID) data1_size," +
        "COUNT(TO_DAYS(INTIME)=TO_DAYS(NOW()) OR NULL) data1_day," +
        "COUNT(STATUS=0 OR NULL) data2_size," +
        "COUNT(TO_DAYS(INTIME)=TO_DAYS(NOW()) AND STATUS=0 OR NULL) data2_day" +
        " FROM EXPRESS";
/**
 * 查询数据库中所有的快递信息
 */
public static final String SQL_FIND_ALL = "SELECT * FROM EXPRESS";
/**
 * 分页查询数据库中所有快递信息
 */
public static final String SQL_FIND_LIMIT = "SELECT * FROM EXPRESS LIMIT ?,?";
/**
 * 通过取件码查询快递信息
 */
public static final String SQL_FIND_BY_CODE = "SELECT * FROM EXPRESS WHERE CODE=?";
/**
 * 通过快递单号查询快递信息
 */
public static final String SQL_FIND__BY_NUMBER = "SELECT * FROM EXPRESS WHERE NUMBER=?";
/**
 * 通过录入手机号查询快递信息
 */
public static final String SQL_FIND_BY_SYSPHONE = "SELECT * FROM EXPRESS WHERE SYSPHONE=?";
/**
 * 通过用户手机号查询快递信息
 */
public static final String SQL_FIND_BY_USERPHONE = "SELECT * FROM EXPRESS WHERE USERPHONE=?";
/**
 * 录入快递
 */
public static final String SQL_INSERT = "INSERT INTO EXPRESS(NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)";
/**
 * 修改快递
 */
public static final String SQL_UPDATE = "UPDATE EXPRESS SET NUMBER=?,USERNAME=?,COMPANY=?,STATUS=? WHERE ID=?";
/**
 * 快递状态码修改(取件)
 */
public static final String SQL_UPDATE_STATUS = "UPDATE EXPRESS SET STATUS=1,OUTTIME=NOW(),CODE=NULL WHERE CODE=?";
/**
 * 快递的删除
 */
public static final String SQL_DELETE = "DELETE FROM EXPRESS WHERE ID=?";


9.1.2 快递相关的dao


步骤:


1.获取数据库连接

2.预编译sql

3.填充参数(可选)

4.执行sql

5.获取执行结果

6.资源释放


创建自定义异常:

 用于记录插入快递数据时因取件码重复而报的异常


package com.wangjiawei.exception;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/4 11:32
 * 4
 */
public class DuplicateCodeException extends Exception{
    /**
     * Constructs a new exception with {@code null} as its detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     */
    public DuplicateCodeException() {
    }
    /**
     * Constructs a new exception with the specified detail message.  The
     * cause is not initialized, and may subsequently be initialized by
     * a call to {@link #initCause}.
     *
     * @param message the detail message. The detail message is saved for
     *                later retrieval by the {@link #getMessage()} method.
     */
    public DuplicateCodeException(String message) {
        super(message);
    }
}


dao接口定义:


package com.wangjiawei.dao;
import com.wangjiawei.bean.Express;
import com.wangjiawei.exception.DuplicateCodeException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/3 13:38
 * 4
 */
public interface BaseExpressDao {
    /**
     * 用于查询数据库中的全部快递(总数,当日新增)
     * 待取件快递(总数,当日新增)
     * @return [{size:总数, day:新增},{size:总数, day:新增}]
     */
    List<Map<String, Integer>> console();
    /**
     * 查询所有快递
     * @param limit 是否分页的标记,true:分页,false:查询所有
     * @param offset sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 快递的集合
     */
    List<Express> findAll(boolean limit, int offset, int pageNumber);
    /**
     * 根据快递单号查询快递信息
     * @param number 单号
     * @return 查询的快递信息,单号不存在时返回null
     */
    Express findByNumber(String number);
    /**
     * 根据快递单号查询快递信息
     * @param code 取件码
     * @return 查询的快递信息,取件码不存在时返回null
     */
    Express findByCode(String code);
    /**
     * 根据用户手机号查询所有快递
     * @param userPhone 手机号
     * @return 查询的快递信息,手机号不存在时返回null
     */
    List<Express> findByUserPhone(String userPhone);
    /**
     * 根据录入人手机号查询录入的所有记录
     * @param sysPhone 手机号
     * @return 查询的快递信息,手机号不存在时返回null
     */
    List<Express> findBySysPhone(String sysPhone);
    /**
     * 快递的录入
     * @param e 要录入的对象
     * @return 录入的结果
     */
    boolean insert(Express e) throws DuplicateCodeException;
    /**
     * 快递的修改
     * @param id 要修改的快递id
     * @param newExpress 新的快递对象(number, company, username, userPhone)
     * @return 修改的结果
     */
    boolean update(int id, Express newExpress);
    /**
     * 更改快递状态为1,表示取件完成
     * @param number 要修改的快递单号
     * @return 修改的结果
     */
    boolean updateStatus(String code);
    /**
     * 根据id,删除单个快递信息
     * @param id 要删除的快递信息
     * @return 删除结果
     */
    boolean delete(int id);
}


dao完整实现:


package com.wangjiawei.dao.imp;
import com.wangjiawei.bean.Express;
import com.wangjiawei.dao.BaseExpressDao;
import com.wangjiawei.exception.DuplicateCodeException;
import com.wangjiawei.util.DruidUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/3 14:16
 * 4
 */
public class ExpressDaoMysql implements BaseExpressDao {
    /**
     * 查询全部快递(总数+新增),待取件快递(总数+新增)
      */
    public static final String SQL_CONSOLE = "SELECT " +
            "COUNT(ID) data1_size," +
            "COUNT(TO_DAYS(INTIME)=TO_DAYS(NOW()) OR NULL) data1_day," +
            "COUNT(STATUS=0 OR NULL) data2_size," +
            "COUNT(TO_DAYS(INTIME)=TO_DAYS(NOW()) AND STATUS=0 OR NULL) data2_day" +
            " FROM EXPRESS";
    /**
     * 查询数据库中所有的快递信息
     */
    public static final String SQL_FIND_ALL = "SELECT * FROM EXPRESS";
    /**
     * 分页查询数据库中所有快递信息
     */
    public static final String SQL_FIND_LIMIT = "SELECT * FROM EXPRESS LIMIT ?,?";
    /**
     * 通过取件码查询快递信息
     */
    public static final String SQL_FIND_BY_CODE = "SELECT * FROM EXPRESS WHERE CODE=?";
    /**
     * 通过快递单号查询快递信息
     */
    public static final String SQL_FIND__BY_NUMBER = "SELECT * FROM EXPRESS WHERE NUMBER=?";
    /**
     * 通过录入手机号查询快递信息
     */
    public static final String SQL_FIND_BY_SYSPHONE = "SELECT * FROM EXPRESS WHERE SYSPHONE=?";
    /**
     * 通过用户手机号查询快递信息
     */
    public static final String SQL_FIND_BY_USERPHONE = "SELECT * FROM EXPRESS WHERE USERPHONE=?";
    /**
     * 录入快递
     */
    public static final String SQL_INSERT = "INSERT INTO EXPRESS(NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)";
    /**
     * 修改快递
     */
    public static final String SQL_UPDATE = "UPDATE EXPRESS SET NUMBER=?,USERNAME=?,COMPANY=?,STATUS=? WHERE ID=?";
    /**
     * 快递状态码修改(取件)
     */
    public static final String SQL_UPDATE_STATUS = "UPDATE EXPRESS SET STATUS=1,OUTTIME=NOW(),CODE=NULL WHERE CODE=?";
    /**
     * 快递的删除
     */
    public static final String SQL_DELETE = "DELETE FROM EXPRESS WHERE ID=?";
    /**
     * 用于查询数据库中的全部快递(总数,当日新增)
     * 待取件快递(总数,当日新增)
     *
     * @return [{size:总数, day:新增},{size:总数, day:新增}]
     */
    @Override
    public List<Map<String, Integer>> console() {
        ArrayList<Map<String, Integer>> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_CONSOLE);
            result = state.executeQuery();
            if (result.next()){
                int data1_size = result.getInt("data1_size");
                int data1_day = result.getInt("data1_day");
                int data2_size = result.getInt("data2_size");
                int data2_day = result.getInt("data2_day");
                Map<String,Integer> data1 = new HashMap<>();
                data1.put("data1_size",data1_size);
                data1.put("data1_day",data1_day);
                Map<String,Integer> data2 = new HashMap<>();
                data2.put("data2_size",data2_size);
                data2.put("data2_day",data2_day);
                data.add(data1);
                data.add(data2);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 查询所有快递
     *
     * @param limit      是否分页的标记,true:分页,false:查询所有
     * @param offset     sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 快递的集合
     */
    @Override
    public List<Express> findAll(boolean limit, int offset, int pageNumber) {
        ArrayList<Express> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            if (limit){
                state = conn.prepareStatement(SQL_FIND_LIMIT);
                state.setInt(1,offset);
                state.setInt(2,pageNumber);
            }else {
                state = conn.prepareStatement(SQL_FIND_ALL);
            }
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inTime");
                Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                data.add(e);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 根据快递单号查询快递信息
     *
     * @param number 单号
     * @return 查询的快递信息,单号不存在时返回null
     */
    @Override
    public Express findByNumber(String number) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND__BY_NUMBER);
            state.setString(1, number);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inTime");
                Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                return e;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 根据快递单号查询快递信息
     *
     * @param code 取件码
     * @return 查询的快递信息,取件码不存在时返回null
     */
    @Override
    public Express findByCode(String code) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_CODE);
            state.setString(1, code);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                Timestamp inTime = result.getTimestamp("inTime");
                Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                return e;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 根据用户手机号查询所有快递
     *
     * @param userPhone 手机号
     * @return 查询的快递信息,手机号不存在时返回null
     */
    @Override
    public List<Express> findByUserPhone(String userPhone) {
        ArrayList<Express> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_USERPHONE);
            state.setString(1,userPhone);
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inTime");
                Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                String sysPhone = result.getString("sysPhone");
                Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                data.add(e);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 根据录入人手机号查询录入的所有记录
     *
     * @param sysPhone 手机号
     * @return 查询的快递信息,手机号不存在时返回null
     */
    @Override
    public List<Express> findBySysPhone(String sysPhone) {
        ArrayList<Express> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_SYSPHONE);
            state.setString(1,sysPhone);
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String number = result.getString("number");
                String username = result.getString("username");
                String userPhone = result.getString("userPhone");
                String company = result.getString("company");
                String code = result.getString("code");
                Timestamp inTime = result.getTimestamp("inTime");
                Timestamp outTime = result.getTimestamp("outTime");
                int status = result.getInt("status");
                Express e = new Express(id, number, username, userPhone, company, code, inTime, outTime, status, sysPhone);
                data.add(e);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 快递的录入
     * INSERT INTO EXPRESS(NUMBER,USERNAME,USERPHONE,COMPANY,CODE,INTIME,STATUS,SYSPHONE) VALUES(?,?,?,?,?,NOW(),0,?)
     * @param e 要录入的对象
     * @return 录入的结果
     */
    @Override
    public boolean insert(Express e) throws DuplicateCodeException{
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_INSERT);
            state.setString(1,e.getNumber());
            state.setString(2,e.getUsername());
            state.setString(3,e.getUserPhone());
            state.setString(4,e.getCompany());
            state.setString(5,e.getCode());
            state.setString(6,e.getSysPhone());
            return (state.executeUpdate() > 0);
        } catch (SQLException e1) {
            /*throwables.printStackTrace();*/
            /*System.out.println(e1.getMessage());*/
            if (e1.getMessage().endsWith("for key 'code'")){
                // 是因为取件码重复而出现了异常
                DuplicateCodeException e2 = new DuplicateCodeException(e1.getMessage());
                throw e2;
            }else {
                e1.printStackTrace();
            }
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }
    /**
     * 快递的修改
     * UPDATE EXPRESS SET NUMBER=?,USERNAME=?,COMPANY=?,STATUS=? WHERE ID=?
     * @param id         要修改的快递id
     * @param newExpress 新的快递对象(number, company, username, userPhone)
     * @return 修改的结果
     */
    @Override
    public boolean update(int id, Express newExpress) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE);
            state.setString(1,newExpress.getNumber());
            state.setString(2,newExpress.getUsername());
            state.setString(3,newExpress.getCompany());
            state.setInt(4,newExpress.getStatus());
            state.setInt(5,id);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
    /**
     * 更改快递状态为1,表示取件完成
     * UPDATE EXPRESS SET STATUS=1 WHERE CODE=?
     * @param code 要取件的取件码
     * @return 修改的结果
     */
    @Override
    public boolean updateStatus(String code) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE_STATUS);
            state.setString(1,code);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
    /**
     * 根据id,删除单个快递信息
     *
     * @param id 要删除的快递信息
     * @return 删除结果
     */
    @Override
    public boolean delete(int id) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_DELETE);
            state.setInt(1,id);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
}


9.2 快递员操作相关的dao


9.2.1 sql语句编写


/**
 * 查询所有快递员(总数 + 新增)
 */
public static final String SQL_CONSOLE = "SELECT " +
        "COUNT(ID) data_size," +
        "COUNT(TO_DAYS(ENROLLTIME)=TO_DAYS(NOW()) OR NULL) data_day " +
        " FROM COURIER";
/**
 * 查询所有快递员
 */
public static final String SQL_FIND_ALL = "SELECT * FROM COURIER";
/**
 * 分页查询数据库中所有快递员
 */
public static final String SQL_FIND_LIMIT = "SELECT * FROM COURIER LIMIT ?,?";
/**
 * 根据id查快递员
 */
public static final String SQL_FIND_BY_ID = "SELECT * FROM COURIER WHERE ID=?";
/**
 * 根据手机号查快递员
 */
public static final String SQL_FIND_BY_PHONE = "SELECT * FROM COURIER WHERE COURIERPHONE=?";
/**
 * 根据姓名查快递员
 */
public static final String SQL_FIND_BY_NAME = "SELECT * FROM COURIER WHERE COURIERNAME=?";
/**
 * 根据身份证号查快递员
 */
public static final String SQL_FIND_BY_ID_NUMBER = "SELECT * FROM COURIER WHERE COURIERIDNUMBER=?";


9.2.2 快递员dao具体实现


接口:


package com.wangjiawei.dao;
import com.wangjiawei.bean.Courier;
import com.wangjiawei.bean.Express;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/8 10:43
 * 4
 */
public interface BaseCourierDao {
    /**
     * 用于查询数据库中的全部快递快递员(总数,当日新增)
     * 快递员(总数,当日新增)
     * @return [{size:总数, day:新增}]
     */
    List<Map<String, Integer>> console();
    /**
     * 查询所有快递员
     * @param limit 是否分页的标记,true:分页,false:查询所有
     * @param offset sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 快递员的集合
     */
    List<Courier> findAll(boolean limit, int offset, int pageNumber);
    /**
     * 根据id查快递员
     * @param id
     * @return 查到的快递员,id不存在时返回null
     */
    Courier findById(int id);
    /**
     * 根据姓名查快递员
     * @param courierName 姓名
     * @return 查到的快递员,courierName不存在时返回null
     */
    Courier findByName(String courierName);
    /**
     * 根据手机号查快递员
     * @param courierPhone 手机号
     * @return 查到的快递员,courierPhone不存在时返回null
     */
    Courier findByPhone(String courierPhone);
    /**
     * 根据身份证号查快递员
     * @param courierIdNumber 身份证号
     * @return 查到的快递员,courierIdNumber不存在时返回null
     */
    Courier findByIdNumber(String courierIdNumber);
    /**
     * 快递员的录入
     * @param c 要录入的对象
     * @return 录入的结果
     */
    boolean insert(Courier c);
    /**
     * 快递员的修改
     * @param id 要修改的快递员id
     * @param newCourier 新的快递员对象
     * @return 修改的结果
     */
    boolean update(int id, Courier newCourier);
    /**
     * 派件数修改
     * @param id 快递员id
     * @param increment 新增的派件数
     * @return 是否修改成功
     */
    boolean updateSendNumber(int id, int increment);
    /**
     * 更新登陆时间
     * @param id
     * @return
     */
    boolean updateLoginTime(int id);
    /**
     * 根据id,删除单个快递员信息
     * @param id 要删除的快递员信息
     * @return 删除结果
     */
    boolean delete(int id);
}


实现类:


package com.wangjiawei.dao.imp;
import com.wangjiawei.bean.Courier;
import com.wangjiawei.bean.Express;
import com.wangjiawei.dao.BaseCourierDao;
import com.wangjiawei.exception.DuplicateCodeException;
import com.wangjiawei.util.DruidUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/8 10:54
 * 4
 */
public class CourierDaoMysql implements BaseCourierDao {
    /**
     * 查询所有快递员(总数 + 新增)
     */
    public static final String SQL_CONSOLE = "SELECT " +
            "COUNT(ID) data_size," +
            "COUNT(TO_DAYS(ENROLLTIME)=TO_DAYS(NOW()) OR NULL) data_day " +
            " FROM COURIER";
    /**
     * 查询所有快递员
     */
    public static final String SQL_FIND_ALL = "SELECT * FROM COURIER";
    /**
     * 分页查询数据库中所有快递员
     */
    public static final String SQL_FIND_LIMIT = "SELECT * FROM COURIER LIMIT ?,?";
    /**
     * 根据id查快递员
     */
    public static final String SQL_FIND_BY_ID = "SELECT * FROM COURIER WHERE ID=?";
    /**
     * 根据手机号查快递员
     */
    public static final String SQL_FIND_BY_PHONE = "SELECT * FROM COURIER WHERE COURIERPHONE=?";
    /**
     * 根据姓名查快递员
     */
    public static final String SQL_FIND_BY_NAME = "SELECT * FROM COURIER WHERE COURIERNAME=?";
    /**
     * 根据身份证号查快递员
     */
    public static final String SQL_FIND_BY_ID_NUMBER = "SELECT * FROM COURIER WHERE COURIERIDNUMBER=?";
    /**
     * 录入快递
     */
    public static final String SQL_INSERT = "INSERT INTO COURIER(COURIERNAME,COURIERPHONE,COURIERIDNUMBER,COURIERPASSWORD,COURIERSENDNUMBER,ENROLLTIME) VALUES(?,?,?,?,0,NOW())";
    /**
     * 修改快递员
     */
    public static final String SQL_UPDATE = "UPDATE COURIER SET COURIERNAME=?,COURIERPHONE=?,COURIERIDNUMBER=?,COURIERPASSWORD=? WHERE ID=?";
    /**
     * 修改快递员派件数
     */
    public static final String SQL_UPDATE_SEND_NUMBER = "UPDATE COURIER SET COURIERSENDNUMBER=COURIERSENDNUMBER+? WHERE ID=?";
    /**
     * 修改快递员登录时间
     */
    public static final String SQL_UPDATE_LOGIN_TIME = "UPDATE COURIER SET LOGINTIME=NOW() WHERE ID=?";
    /**
     * 快递员的删除
     */
    public static final String SQL_DELETE = "DELETE FROM COURIER WHERE ID=?";
    /**
     * 用于查询数据库中的全部快递快递员(总数,当日新增)
     * 快递员(总数,当日新增)
     *
     * @return [{size:总数, day:新增}]
     */
    @Override
    public List<Map<String, Integer>> console() {
        ArrayList<Map<String, Integer>> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_CONSOLE);
            result = state.executeQuery();
            if (result.next()){
                int data_size = result.getInt("data_size");
                int data_day = result.getInt("data_day");
                Map<String,Integer> data1 = new HashMap<>();
                data1.put("data_size",data_size);
                data1.put("data_day",data_day);
                data.add(data1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 查询所有快递员
     *
     * @param limit      是否分页的标记,true:分页,false:查询所有
     * @param offset     sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 快递员的集合
     */
    @Override
    public List<Courier> findAll(boolean limit, int offset, int pageNumber) {
        ArrayList<Courier> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            if (limit){
                state = conn.prepareStatement(SQL_FIND_LIMIT);
                state.setInt(1,offset);
                state.setInt(2,pageNumber);
            }else {
                state = conn.prepareStatement(SQL_FIND_ALL);
            }
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String courierName = result.getString("courierName");
                String courierPhone = result.getString("courierPhone");
                String courierIdNumber = result.getString("courierIdNumber");
                String courierPassword = result.getString("courierPassword");
                int courierSendNumber = result.getInt("courierSendNumber");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                Courier c = new Courier(id, courierName, courierPhone, courierIdNumber, courierPassword, courierSendNumber, enrollTime, loginTime);
                data.add(c);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 根据id查快递员
     *
     * @param id
     * @return 查到的快递员,id不存在时返回null
     */
    @Override
    public Courier findById(int id) {
        ArrayList<Courier> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_ID);
            state.setInt(1, id);
            result = state.executeQuery();
            if (result.next()){
                String courierName = result.getString("courierName");
                String courierPhone = result.getString("courierPhone");
                String courierIdNumber = result.getString("courierIdNumber");
                String courierPassword = result.getString("courierPassword");
                int courierSendNumber = result.getInt("courierSendNumber");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                Courier c = new Courier(id, courierName, courierPhone, courierIdNumber, courierPassword, courierSendNumber, enrollTime, loginTime);
                return c;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 根据姓名查快递员
     *
     * @param courierName 姓名
     * @return 查到的快递员,courierName不存在时返回null
     */
    @Override
    public Courier findByName(String courierName) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_NAME);
            state.setString(1, courierName);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String courierPhone = result.getString("courierPhone");
                String courierIdNumber = result.getString("courierIdNumber");
                String courierPassword = result.getString("courierPassword");
                int courierSendNumber = result.getInt("courierSendNumber");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                Courier c = new Courier(id, courierName, courierPhone, courierIdNumber, courierPassword, courierSendNumber, enrollTime, loginTime);
                return c;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 根据手机号查快递员
     *
     * @param courierPhone 手机号
     * @return 查到的快递员,courierPhone不存在时返回null
     */
    @Override
    public Courier findByPhone(String courierPhone) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_PHONE);
            state.setString(1, courierPhone);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String courierName = result.getString("courierName");
                String courierIdNumber = result.getString("courierIdNumber");
                String courierPassword = result.getString("courierPassword");
                int courierSendNumber = result.getInt("courierSendNumber");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                Courier c = new Courier(id, courierName, courierPhone, courierIdNumber, courierPassword, courierSendNumber, enrollTime, loginTime);
                return c;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 根据身份证号查快递员
     *
     * @param courierIdNumber 身份证号
     * @return 查到的快递员,courierIdNumber不存在时返回null
     */
    @Override
    public Courier findByIdNumber(String courierIdNumber) {
        ArrayList<Courier> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_ID_NUMBER);
            state.setString(1, courierIdNumber);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String courierName = result.getString("courierName");
                String courierPhone = result.getString("courierPhone");
                String courierPassword = result.getString("courierPassword");
                int courierSendNumber = result.getInt("courierSendNumber");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                Courier c = new Courier(id, courierName, courierPhone, courierIdNumber, courierPassword, courierSendNumber, enrollTime, loginTime);
                return c;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 快递员的录入
     * "INSERT INTO COURIER(COURIERNAME,COURIERPHONE,COURIERIDNUMBER,COURIERPASSWORD,COURIERSENDNUMBER,ENROLLTIME) VALUES(?,?,?,?,0,NOW())"
     * @param c 要录入的对象
     * @return 录入的结果
     */
    @Override
    public boolean insert(Courier c) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_INSERT);
            state.setString(1,c.getCourierName());
            state.setString(2,c.getCourierPhone());
            state.setString(3,c.getCourierIdNumber());
            state.setString(4,c.getCourierPassword());
            return (state.executeUpdate() > 0);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }
    /**
     * 快递员的修改
     * "UPDATE COURIER SET COURIERNAME=?,COURIERPHONE=?,COURIERIDNUMBER=?,COURIERPASSWORD=? WHERE ID=?"
     * @param id         要修改的快递员id
     * @param newCourier 新的快递员对象
     * @return 修改的结果
     */
    @Override
    public boolean update(int id, Courier newCourier) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE);
            state.setString(1,newCourier.getCourierName());
            state.setString(2,newCourier.getCourierPhone());
            state.setString(3,newCourier.getCourierIdNumber());
            state.setString(4,newCourier.getCourierPassword());
            state.setInt(5,id);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
    /**
     * 派件数修改
     *
     * @param id        快递员id
     * @param increment 新增的派件数
     * @return 是否修改成功
     */
    @Override
    public boolean updateSendNumber(int id, int increment) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE_SEND_NUMBER);
            state.setInt(1,increment);
            state.setInt(2,id);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
    /**
     * 更新登陆时间
     *
     * @param id
     * @return
     */
    @Override
    public boolean updateLoginTime(int id) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            state.setInt(1,id);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
    /**
     * 根据id,删除单个快递员信息
     *
     * @param id 要删除的快递员信息
     * @return 删除结果
     */
    @Override
    public boolean delete(int id) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_DELETE);
            state.setInt(1,id);
            return state.executeUpdate() > 0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
}


9.3.2 用户相关dao


步骤:


1.获取数据库连接

2.预编译sql

3.填充参数(可选)

4.执行sql

5.获取执行结果

6.资源释放


dao接口定义:


package com.wangjiawei.dao;
import com.wangjiawei.bean.User;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/9 9:54
 * 4
 */
public interface BaseUserDao {
    /**
     * 用于查询数据库中的全部用户(总数,当日新增)
     * @return [{size:总数, day:新增}]
     */
    List<Map<String, Integer>> console();
    /**
     * 查询所有用户
     * @param limit 是否分页的标记,true:分页,false:查询所有
     * @param offset sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 用户的集合
     */
    List<User> findAll(boolean limit, int offset, int pageNumber);
    /**
     * 根据用户名查询用户
     * @param userName 用户名
     * @return
     */
    List<User> findByName(String userName);
    /**
     * 根据身份证号查询用户
     * @param userIdNumber 身份证号
     * @return 查询结果
     */
    User findByIdNumber(String userIdNumber);
    /**
     * 根据手机号查询用户
     * @param userPhone 手机号
     * @return
     */
    User findByUserPhone(String userPhone);
    /**
     * 用户录入
     * @param u 要录入的对象
     * @return 录入的结果
     */
    boolean insert(User u);
    /**
     * 用户的修改
     * @param id 要修改用户的id
     * @param newUser 新的用户对象
     * @return 修改的结果
     */
    boolean update(int id, User newUser);
    /**
     * 更新登录时间
     * @param id
     * @return
     */
    boolean updateLoginTime(int id);
    /**
     * 根据id,删除单个用户信息
     * @param id 要删除的用户信息
     * @return 删除结果
     */
    boolean delete(int id);
}


dao完整实现:


package com.wangjiawei.dao.imp;
import com.wangjiawei.bean.User;
import com.wangjiawei.dao.BaseUserDao;
import com.wangjiawei.util.DruidUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/9 10:07
 * 4
 */
public class UserDaoMysql implements BaseUserDao {
    /**
     * 查询用户(总数+新增)
     */
    public static final String SQL_CONSOLE = "SELECT " +
            "COUNT(ID) data_size," +
            "COUNT(TO_DAYS(ENROLLTIME)=TO_DAYS(NOW()) OR NULL) data_day " +
            "FROM USER";
    /**
     * 查询数据库中所有的用户信息
     */
    public static final String SQL_FIND_ALL = "SELECT * FROM USER";
    /**
     * 分页查询数据库中所有用户信息
     */
    public static final String SQL_FIND_LIMIT = "SELECT * FROM USER LIMIT ?,?";
    /**
     * 通过用户名查询用户信息
     */
    public static final String SQL_FIND_BY_USER_NAME = "SELECT * FROM USER WHERE USERNAME=?";
    /**
     * 通过手机号查询用户信息
     */
    public static final String SQL_FIND_BY_USER_PHONE = "SELECT * FROM USER WHERE USERPHONE=?";
    public static final String SQL_FIND_BY_USER_ID_NUMBER = "SELECT * FROM USER WHERE USERIDNUMBER=?";
    /**
     * 录入用户
     */
    public static final String SQL_INSERT = "INSERT INTO USER(USERNAME,USERPHONE,USERIDNUMBER,USERPASSWORD,ENROLLTIME,LOGINTIME) VALUES(?,?,?,?,NOW(),NOW())";
    /**
     * 修改用户
     */
    public static final String SQL_UPDATE = "UPDATE USER SET USERNAME=?,USERPHONE=?,USERIDNUMBER=?,USERPASSWORD=? WHERE ID=?";
    /**
     * 修改用户登录时间
     */
    public static final String SQL_UPDATE_LOGIN_TIME = "UPDATE USER SET LOGINTIME=NOW() WHERE ID=?";
    /**
     * 快递员的删除
     */
    public static final String SQL_DELETE = "DELETE FROM USER WHERE ID=?";
    /**
     * 用于查询数据库中的全部用户(总数,当日新增)
     *
     * @return [{size:总数, day:新增}]
     */
    @Override
    public List<Map<String, Integer>> console() {
        ArrayList<Map<String, Integer>> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_CONSOLE);
            result = state.executeQuery();
            if (result.next()){
                int data_size = result.getInt("data_size");
                int data_day = result.getInt("data_day");
                Map<String,Integer> data1 = new HashMap<>();
                data1.put("data_size",data_size);
                data1.put("data_day",data_day);
                data.add(data1);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 查询所有用户
     *
     * @param limit      是否分页的标记,true:分页,false:查询所有
     * @param offset     sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 用户的集合
     */
    @Override
    public List<User> findAll(boolean limit, int offset, int pageNumber) {
        ArrayList<User> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            if (limit){
                state = conn.prepareStatement(SQL_FIND_LIMIT);
                state.setInt(1,offset);
                state.setInt(2,pageNumber);
            }else {
                state = conn.prepareStatement(SQL_FIND_ALL);
            }
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String userName = result.getString("userName");
                String userPhone = result.getString("userPhone");
                String userIdNumber = result.getString("userIdNumber");
                String userPassword = result.getString("userPassword");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                User u = new User(id, userName, userPhone, userIdNumber, userPassword, enrollTime, loginTime);
                data.add(u);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 根据用户名查询用户
     *
     * @param userName 用户名
     * @return
     */
    @Override
    public List<User> findByName(String userName) {
        ArrayList<User> data = new ArrayList<>();
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_USER_NAME);
            state.setString(1,userName);
            result = state.executeQuery();
            while (result.next()){
                int id = result.getInt("id");
                String userPhone = result.getString("userPhone");
                String userIdNumber = result.getString("userIdNumber");
                String userPassword = result.getString("userPassword");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                User u = new User(id, userName, userPhone, userIdNumber, userPassword, enrollTime, loginTime);
                data.add(u);
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
    /**
     * 根据身份证号查询用户
     *
     * @param userIdNumber 身份证号
     * @return 查询结果
     */
    @Override
    public User findByIdNumber(String userIdNumber) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_USER_ID_NUMBER);
            state.setString(1, userIdNumber);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String userName = result.getString("userName");
                String userPhone = result.getString("userPhone");
                String userPassword = result.getString("userPassword");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                User u = new User(id, userName, userPhone, userIdNumber, userPassword, enrollTime, loginTime);
                return u;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 根据手机号查询用户
     *
     * @param userPhone 手机号
     * @return
     */
    @Override
    public User findByUserPhone(String userPhone) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            state = conn.prepareStatement(SQL_FIND_BY_USER_PHONE);
            state.setString(1, userPhone);
            result = state.executeQuery();
            if (result.next()){
                int id = result.getInt("id");
                String userName = result.getString("userName");
                String userIdNumber = result.getString("userIdNumber");
                String userPassword = result.getString("userPassword");
                Timestamp enrollTime = result.getTimestamp("enrollTime");
                Timestamp loginTime = result.getTimestamp("loginTime");
                User u = new User(id, userName, userPhone, userIdNumber, userPassword, enrollTime, loginTime);
                return u;
            }
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,result);
        }
        return null;
    }
    /**
     * 用户录入
     *
     * @param u 要录入的对象
     * @return 录入的结果
     */
    @Override
    public boolean insert(User u) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_INSERT);
            state.setString(1,u.getUserName());
            state.setString(2,u.getUserPhone());
            state.setString(3,u.getUserIdNumber());
            state.setString(4,u.getUserPassword());
            return (state.executeUpdate() > 0);
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }
    /**
     * 用户的修改
     *
     * @param id      要修改用户的id
     * @param newUser 新的用户对象
     * @return 修改的结果
     */
    @Override
    public boolean update(int id, User newUser) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE);
            state.setString(1,newUser.getUserName());
            state.setString(2,newUser.getUserPhone());
            state.setString(3,newUser.getUserIdNumber());
            state.setString(4,newUser.getUserPassword());
            state.setInt(5,id);
            return state.executeUpdate() > 0;
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }
    /**
     * 更新登录时间
     *
     * @param id
     * @return
     */
    @Override
    public boolean updateLoginTime(int id) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            state.setInt(1,id);
            return state.executeUpdate() > 0;
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }
    /**
     * 根据id,删除单个用户信息
     *
     * @param id 要删除的用户信息
     * @return 删除结果
     */
    @Override
    public boolean delete(int id) {
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        try {
            state = conn.prepareStatement(SQL_DELETE);
            state.setInt(1, id);
            return state.executeUpdate() > 0;
        }catch (SQLException throwables){
            throwables.printStackTrace();
        }finally {
            DruidUtil.close(conn,state,null);
        }
        return false;
    }
}


10 service层编写


10.1 ExpressService


package com.wangjiawei.service;
import com.wangjiawei.bean.Express;
import com.wangjiawei.dao.BaseExpressDao;
import com.wangjiawei.dao.imp.ExpressDaoMysql;
import com.wangjiawei.exception.DuplicateCodeException;
import com.wangjiawei.util.RandomUtil;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/4 14:03
 * 4
 */
public class ExpressService {
    private static BaseExpressDao dao = new ExpressDaoMysql();
    /**
     * 用于查询数据库中的全部快递(总数,当日新增)
     * 待取件快递(总数,当日新增)
     *
     * @return [{size:总数, day:新增},{size:总数, day:新增}]
     */
    public static List<Map<String, Integer>> console() {
        return dao.console();
    }
    /**
     * 查询所有快递
     *
     * @param limit      是否分页的标记,true:分页,false:查询所有
     * @param offset     sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 快递的集合
     */
    public static List<Express> findAll(boolean limit, int offset, int pageNumber) {
        return dao.findAll(limit, offset, pageNumber);
    }
    /**
     * 根据快递单号查询快递信息
     *
     * @param number 单号
     * @return 查询的快递信息,单号不存在时返回null
     */
    public static Express findByNumber(String number) {
        return dao.findByNumber(number);
    }
    /**
     * 根据快递单号查询快递信息
     *
     * @param code 取件码
     * @return 查询的快递信息,取件码不存在时返回null
     */
    public static Express findByCode(String code) {
        return dao.findByCode(code);
    }
    /**
     * 根据用户手机号查询所有快递
     *
     * @param userPhone 手机号
     * @return 查询的快递信息,手机号不存在时返回null
     */
    public static List<Express> findByUserPhone(String userPhone) {
        return dao.findByUserPhone(userPhone);
    }
    /**
     * 根据录入人手机号查询录入的所有记录
     *
     * @param sysPhone 手机号
     * @return 查询的快递信息,手机号不存在时返回null
     */
    public static List<Express> findBySysPhone(String sysPhone) {
        return dao.findBySysPhone(sysPhone);
    }
    /**
     * 快递的录入
     *
     * @param e 要录入的对象
     * @return 录入的结果
     */
    public static boolean insert(Express e) {
        // 生成取件码
        e.setCode(RandomUtil.getCode() + "");
        try {
            return dao.insert(e);
        } catch (DuplicateCodeException duplicateCodeException) {
            // 取件码重复
            return insert(e);
        }
    }
    /**
     * 快递的修改
     *
     * @param id         要修改的快递id
     * @param newExpress 新的快递对象(number, company, username, userPhone)
     * @return 修改的结果
     */
    public static boolean update(int id, Express newExpress) {
        if (newExpress.getUserPhone() != null){
            // 手机号码变了
            dao.delete(id);
            return insert(newExpress);
        }else{
            boolean update = dao.update(id, newExpress);
            Express e = dao.findByNumber(newExpress.getNumber());
            if (newExpress.getStatus() == 1){
                // 更改为已取件
                updateStatus(e.getCode());
            }
            return update;
        }
    }
    /**
     * 更改快递状态为1,表示取件完成
     *
     * @param code@return 修改的结果
     */
    public static boolean updateStatus(String code) {
        return dao.updateStatus(code);
    }
    /**
     * 根据id,删除单个快递信息
     *
     * @param id 要删除的快递信息
     * @return 删除结果
     */
    public static boolean delete(int id) {
        return dao.delete(id);
    }
}


10.2 快递员service层实现


package com.wangjiawei.service;
import com.wangjiawei.bean.Courier;
import com.wangjiawei.dao.BaseCourierDao;
import com.wangjiawei.dao.imp.CourierDaoMysql;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/8 16:52
 * 4
 */
public class CourierService{
    private static BaseCourierDao dao = new CourierDaoMysql();
    /**
     * 用于查询数据库中的全部快递快递员(总数,当日新增)
     * 快递员(总数,当日新增)
     *
     * @return [{size:总数, day:新增}]
     */
    public static List<Map<String, Integer>> console() {
        return dao.console();
    }
    /**
     * 查询所有快递员
     *
     * @param limit      是否分页的标记,true:分页,false:查询所有
     * @param offset     sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 快递员的集合
     */
    public static List<Courier> findAll(boolean limit, int offset, int pageNumber) {
        return dao.findAll(limit, offset, pageNumber);
    }
    /**
     * 根据id查快递员
     *
     * @param id
     * @return 查到的快递员,id不存在时返回null
     */
    public static Courier findById(int id) {
        return dao.findById(id);
    }
    /**
     * 根据姓名查快递员
     *
     * @param courierName 姓名
     * @return 查到的快递员,courierName不存在时返回null
     */
    public static Courier findByName(String courierName) {
        return dao.findByName(courierName);
    }
    /**
     * 根据手机号查快递员
     *
     * @param courierPhone 手机号
     * @return 查到的快递员,courierPhone不存在时返回null
     */
    public static Courier findByPhone(String courierPhone) {
        return dao.findByPhone(courierPhone);
    }
    /**
     * 根据身份证号查快递员
     *
     * @param courierIdNumber 身份证号
     * @return 查到的快递员,courierIdNumber不存在时返回null
     */
    public static Courier findByIdNumber(String courierIdNumber) {
        return dao.findByIdNumber(courierIdNumber);
    }
    /**
     * 快递员的录入
     *
     * @param c 要录入的对象
     * @return 录入的结果
     */
    public static boolean insert(Courier c) {
        return dao.insert(c);
    }
    /**
     * 快递员的修改
     *
     * @param id         要修改的快递员id
     * @param newCourier 新的快递员对象
     * @return 修改的结果
     */
    public static boolean update(int id, Courier newCourier) {
        return dao.update(id,newCourier);
    }
    /**
     * 根据id,删除单个快递员信息
     *
     * @param id 要删除的快递员信息
     * @return 删除结果
     */
    public static boolean delete(int id) {
        return dao.delete(id);
    }
    /**
     * 派件数修改
     * @param id 快递员id
     * @param increment 新增的派件数
     * @return 是否修改成功
     */
    public static boolean updateSendNumber(int id, int increment){
        return dao.updateSendNumber(id, increment);
    }
    /**
     * 更新登陆时间
     * @param id
     * @return
     */
    public static boolean updateLoginTime(int id){
        return dao.updateLoginTime(id);
    }
}


10.3 用户service层实现


package com.wangjiawei.service;
import com.wangjiawei.bean.User;
import com.wangjiawei.dao.BaseUserDao;
import com.wangjiawei.dao.imp.UserDaoMysql;
import java.util.List;
import java.util.Map;
/**
 * 2 * @Author: 小王同学
 * 3 * @Date: 2020/10/9 14:02
 * 4
 */
public class UserService {
    private static BaseUserDao dao = new UserDaoMysql();
    /**
     * 用于查询数据库中的全部用户(总数,当日新增)
     *
     * @return [{size:总数, day:新增}]
     */
    public List<Map<String, Integer>> console() {
        return dao.console();
    }
    /**
     * 查询所有用户
     *
     * @param limit      是否分页的标记,true:分页,false:查询所有
     * @param offset     sql语句的起始索引
     * @param pageNumber 每一页查询的数量
     * @return 用户的集合
     */
    public List<User> findAll(boolean limit, int offset, int pageNumber) {
        return dao.findAll(limit, offset, pageNumber);
    }
    /**
     * 根据用户名查询用户
     *
     * @param userName 用户名
     * @return
     */
    public List<User> findByName(String userName) {
        return dao.findByName(userName);
    }
    /**
     * 根据身份证号查询用户
     *
     * @param userIdNumber 身份证号
     * @return 查询结果
     */
    public User findByIdNumber(String userIdNumber) {
        return dao.findByIdNumber(userIdNumber);
    }
    /**
     * 根据手机号查询用户
     *
     * @param userPhone 手机号
     * @return
     */
    public User findByUserPhone(String userPhone) {
        return dao.findByUserPhone(userPhone);
    }
    /**
     * 用户录入
     *
     * @param u 要录入的对象
     * @return 录入的结果
     */
    public boolean insert(User u) {
        return dao.insert(u);
    }
    /**
     * 用户的修改
     *
     * @param id      要修改用户的id
     * @param newUser 新的用户对象
     * @return 修改的结果
     */
    public boolean update(int id, User newUser) {
        return dao.update(id, newUser);
    }
    /**
     * 更新登录时间
     *
     * @param id
     * @return
     */
    public boolean updateLoginTime(int id) {
        return dao.updateLoginTime(id);
    }
    /**
     * 根据id,删除单个用户信息
     *
     * @param id 要删除的用户信息
     * @return 删除结果
     */
    public boolean delete(int id) {
        return dao.delete(id);
    }
}


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1月前
|
存储 算法
非递归实现后序遍历时,如何避免栈溢出?
后序遍历的递归实现和非递归实现各有优缺点,在实际应用中需要根据具体的问题需求、二叉树的特点以及性能和空间的限制等因素来选择合适的实现方式。
30 1
|
8天前
|
NoSQL Java 关系型数据库
Liunx部署java项目Tomcat、Redis、Mysql教程
本文详细介绍了如何在 Linux 服务器上安装和配置 Tomcat、MySQL 和 Redis,并部署 Java 项目。通过这些步骤,您可以搭建一个高效稳定的 Java 应用运行环境。希望本文能为您在实际操作中提供有价值的参考。
63 26
|
20天前
|
XML Java 测试技术
从零开始学 Maven:简化 Java 项目的构建与管理
Maven 是一个由 Apache 软件基金会开发的项目管理和构建自动化工具。它主要用在 Java 项目中,但也可以用于其他类型的项目。
31 1
从零开始学 Maven:简化 Java 项目的构建与管理
|
17天前
|
存储 算法 Java
Java 内存管理与优化:掌控堆与栈,雕琢高效代码
Java内存管理与优化是提升程序性能的关键。掌握堆与栈的运作机制,学习如何有效管理内存资源,雕琢出更加高效的代码,是每个Java开发者必备的技能。
45 5
|
19天前
|
存储 缓存 算法
在C语言中,数据结构是构建高效程序的基石。本文探讨了数组、链表、栈、队列、树和图等常见数据结构的特点、应用及实现方式
在C语言中,数据结构是构建高效程序的基石。本文探讨了数组、链表、栈、队列、树和图等常见数据结构的特点、应用及实现方式,强调了合理选择数据结构的重要性,并通过案例分析展示了其在实际项目中的应用,旨在帮助读者提升编程能力。
42 5
|
19天前
|
Java
Java项目中高精度数值计算:为何BigDecimal优于Double
在Java项目开发中,涉及金额计算、面积计算等高精度数值操作时,应选择 `BigDecimal` 而非 `Double`。`BigDecimal` 提供任意精度的小数运算、多种舍入模式和良好的可读性,确保计算结果的准确性和可靠性。例如,在金额计算中,`BigDecimal` 可以精确到小数点后两位,而 `Double` 可能因精度问题导致结果不准确。
|
29天前
|
Java Android开发
Eclipse 创建 Java 项目
Eclipse 创建 Java 项目
39 4
|
26天前
|
算法
数据结构之购物车系统(链表和栈)
本文介绍了基于链表和栈的购物车系统的设计与实现。该系统通过命令行界面提供商品管理、购物车查看、结算等功能,支持用户便捷地管理购物清单。核心代码定义了商品、购物车商品节点和购物车的数据结构,并实现了添加、删除商品、查看购物车内容及结算等操作。算法分析显示,系统在处理小规模购物车时表现良好,但在大规模购物车操作下可能存在性能瓶颈。
42 0
|
1月前
|
C语言
【数据结构】栈和队列(c语言实现)(附源码)
本文介绍了栈和队列两种数据结构。栈是一种只能在一端进行插入和删除操作的线性表,遵循“先进后出”原则;队列则在一端插入、另一端删除,遵循“先进先出”原则。文章详细讲解了栈和队列的结构定义、方法声明及实现,并提供了完整的代码示例。栈和队列在实际应用中非常广泛,如二叉树的层序遍历和快速排序的非递归实现等。
163 9
|
1月前
|
存储 算法 Java
数据结构的栈
栈作为一种简单而高效的数据结构,在计算机科学和软件开发中有着广泛的应用。通过合理地使用栈,可以有效地解决许多与数据存储和操作相关的问题。