0


JavaWeb阶段案例--简易版管理图书系统(增删改查)

1. 创建数据库及数据表

#创建数据库jdbc
CREATE DATABASE jdbc ;

#打开数据库
USE jdbc ;

#创建用户表 t_user
CREATE TABLE t_user(
    id int PRIMARY KEY auto_increment,
    username VARCHAR(20),
    password VARCHAR(20),
    sex VARCHAR(2),
    hobby VARCHAR(20),
    city VARCHAR(20),
    signature VARCHAR(200)
);

#创建图书表 t_book
CREATE TABLE t_book(
    id int PRIMARY KEY auto_increment,
    bookname VARCHAR(20),
    price FLOAT ,
    author VARCHAR(20)
);

#在两个表中插入分别插入一条数据
INSERT INTO t_user VALUES(NULL,'admin','123','男','足球','济南','我是admin');
INSERT INTO t_book VALUES(NULL,'JavaWeb教程','50','李四');

2.在idea中创建一个JavaWeb项目

  1. 在WEB-INF下创建一个lib包,并导入以下jar包:(导入后,鼠标右键选中lib文件夹,单击“add as lib...”

注:使用Lombok包时,除了需要导入jar包还需要从idea中下载Lombok插件

  1. file -- setting -- plugins -- 搜Lombok -- 勾选上 -- Apply -- OK
  2. file -- setting -- Build Exec..... -- Compiler -- Annotation Processors -- 勾选Enable annotation processing

3.在web下创建4个jsp和1和html

  1. 4个jsp(addBook.jsp 、 bookList.jsp 、 index.jsp 、 updateBook.jsp)
  2. 1个html(register.html)

** **** 1. 创建addBook.jsp**


<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>添加图书</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>

    <!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>

    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <h2 class="text-center my-4">新增图书</h2>

    <div class="row">
        <p class="col-md-5 offset-md-7">欢迎您,${loginUser.username}</p>
        <div class="col-md-4 offset-md-4">
            <form action="addbookservlet" method="post" >
                <table class="table table-bordered">
                    <tr>
                        <td>图书名称:</td>
                        <td><input type="text" class="form-control" name="bookname" placeholder="请输入图书名称" id="bookname"></td>
                    </tr>
                    <tr>
                        <td>图书价格:</td>
                        <td><input type="text" class="form-control" name="price" placeholder="请输入图书价格" id="price"></td>
                    </tr>
                    <tr>
                        <td>图书作者:</td>
                        <td><input type="text" class="form-control" name="author" placeholder="请输入图书作者" id="author"></td>
                    </tr>

                    <tr>
                        <td colspan="2"><button type="submit" class="btn btn-primary">提交</button></td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
</div>
</body>
</html>

** 2. 创建bookList.jsp**

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
    <title>图书列表</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>

    <!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>

    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container-fluid">
    <h2 class="text-center my-4">图书列表</h2>
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <p class="col-md-3 offset-md-9">欢迎您,${loginUser.username}</p>
            <a class="btn btn-primary my-2" href="addBook.jsp">新增图书</a>
            <table class="table  table-hover">
                <thead>
                <tr>
                    <th>编号</th>
                    <th>图书名称</th>
                    <th>价格</th>
                    <th>作者</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>

                <c:forEach var="book" items="${list}">
                <tr>
                    <td>${book.id}</td>
                    <td>${book.bookname}</td>
                    <td>${book.price}</td>
                    <td>${book.author}</td>
                    <td>
                        <a href="getBookInfoById?id=${book.id}" class="btn btn-primary">修改</a>
                        <button class="btn btn-danger" data-toggle="modal" data-target="#myModal" onclick="transId(${book.id})">删除</button>
                    </td>
                </tr>
                </c:forEach>

                </tbody>
            </table>
        </div>
    </div>

    <!-- 模态框 -->
    <div class="modal fade" id="myModal">
        <div class="modal-dialog">
            <div class="modal-content">

                <!-- 模态框头部 -->
                <div class="modal-header">
                    <h4 class="modal-title">提示</h4>
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>
                <input type="hidden" id="bookid" value="">
                <!-- 模态框主体 -->
                <div class="modal-body">
                    确认删除该信息吗?
                </div>

                <!-- 模态框底部 -->
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="doDelete()">确定</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>

            </div>
        </div>
    </div>
</div>

<script>
    function transId(id){
        //jQuery -- $("#bookid") 从页面上寻找id属性为bookid的元素
        $("#bookid").val(id); //jQuery写法

       // document.getElementById("bookid").value = id ; //javaScript写法
    }
    function doDelete(){
        window.location = "delBook?id="+ $("#bookid").val(); //jQuery写法

        // window.location = "delBook?id="+document.getElementById("bookid").value ; //javaScript写法
    }
</script>
</body>
</html>

** 3. 创建index.jsp**


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html>
<head>
  <title>登录</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- 新 Bootstrap4 核心 CSS 文件 -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

  <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
  <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>

  <!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
  <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>

  <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
  <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
  <h2 class="text-center">登录</h2>
  <div class="row">
    <div class="col-md-4 offset-md-4">

      <!-- 菜鸟教程https://www.runoob.com -- 学习Bootstrap4 -->
      <c:if test="${!empty errmsg}">
        <div class="alert alert-danger alert-dismissible">
          <button type="button" class="close" data-dismiss="alert">&times;</button>
          <strong>错误!</strong> ${errmsg}
        </div>
      </c:if>

      <form action="loginservlet" method="post">
        <div class="form-group">
          <label for="username">账号:</label>
          <input type="text" class="form-control" id="username" name="username" placeholder="请输入用户名" value="${cookie.username.value}">
        </div>
        <div class="form-group">
          <label for="password">密码:</label>
          <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码" value="${cookie.password.value}">
        </div>
        <div class="form-check">
          <label class="form-check-label center-block">
            <input class="form-check-input" type="checkbox" name="remeber" ${(empty cookie.username)?"":"checked"} > 记住密码
          </label>
        </div>
        <button type="submit" class="btn btn-primary mt-4 mx-auto">登录</button>
        <a href="register.html" style="    display: inline-block;margin-right: 10px; width: 64px; height: 40px; float: right; margin-top: 36px;">免费注册</a>
      </form>
    </div>
  </div>
  <div class="text-center text-info">
    Tips:账号:admin 密码:123
  </div>
</div>
</form>
</body>
</html>

** 4. 创建updateBook.jsp**

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>修改图书</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>

    <!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>

    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <h2 class="text-center my-4">修改图书</h2>
    <div class="row">
        <p class="col-md-5 offset-md-7">欢迎您,${loginUser.username}</p>
        <div class="col-md-4 offset-md-4">
            <form action="uptBook" method="post">
                <input type="hidden" name="id" value="${book.id}">
                <table class="table table-bordered">
                    <tr>
                        <td>图书名称:</td>
                        <td><input type="text" class="form-control" name="bookname" placeholder="请输入图书名称" id="bookname"
                                   value="${book.bookname}"></td>
                    </tr>
                    <tr>
                        <td>图书价格:</td>
                        <td><input type="text" class="form-control" name="price" placeholder="请输入图书价格" id="price"
                                   value="${book.price}"></td>
                    </tr>
                    <tr>
                        <td>图书作者:</td>
                        <td><input type="text" class="form-control" name="author" placeholder="请输入图书作者" id="author"
                                   value="${book.author}"></td>
                    </tr>

                    <tr>
                        <td colspan="2">
                            <button type="submit" class="btn btn-primary">提交</button>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
</div>
</body>
</html>

** 5. 创建register.html**


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- 新 Bootstrap4 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>

    <!-- bootstrap.bundle.min.js 用于弹窗、提示、下拉菜单,包含了 popper.min.js -->
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>

    <!-- 最新的 Bootstrap4 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <h2 class="text-center my-4">注册账号</h2>
    <div class="row">
        <div class="col-md-4 offset-md-4">
            <form action="registerservlet" method="post">
                <table class="table table-bordered">
                    <tr>
                        <td>账号:</td>
                        <td><input type="text" class="form-control" name="username" placeholder="请输入账号" id="username">
                        </td>
                    </tr>
                    <tr>
                        <td>密码:</td>
                        <td><input type="password" class="form-control" name="password" placeholder="请输入密码"
                                   id="password"></td>
                    </tr>
                    <tr>
                        <td>性别:</td>
                        <td>
                            <label class="form-inline">
                                <label><input type="radio" class="form-control" name="sex" value="男">男</label><br>
                                <label><input type="radio" class="form-control" name="sex" value="女">女</label>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <td>爱好:</td>
                        <td>
                            <label class="form-inline">
                                <label class="form-check-label"><input type="checkbox" class="form-control" name="hobby"
                                                                       value="足球">足球</label>
                                <label class="form-check-label"><input type="checkbox" class="form-control" name="hobby"
                                                                       value="篮球">篮球</label>
                                <label class="form-check-label"><input type="checkbox" class="form-control" name="hobby"
                                                                       value="乒乓球">乒乓球</label>
                                <label class="form-check-label"><input type="checkbox" class="form-control" name="hobby"
                                                                       value="唱歌">唱歌</label>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <td>所在城市:</td>
                        <td>
                            <select name="city">
                                <option value="济南">济南</option>
                                <option value="青岛">青岛</option>
                                <option value="济宁">济宁</option>
                                <option value="临沂">临沂</option>
                                <option value="泰安">泰安</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td>个性签名:</td>
                        <td>
                            <textarea name="signature"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <button type="submit" class="btn btn-primary">提交</button>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
</div>
</body>
</html>

4.在src下创建4个文件夹

  1. 创建controller文件夹 --放servlet文件
  2. 创建dao文件夹 --放interface接口 ------在dao下创建文件夹impl --放实现接口的方法
  3. 创建enity文件夹 --放对象类
  4. 创建util文件夹 --放定义的方法(例如:连接数据库的方法)
  5. 直接创建一个Test的Java类 --用于在控制台测试

1. 创建controller文件夹,并创建以下servlet

** 1.创建 addBookServlet**

import com.individual.dao.BookDao;
import com.individual.dao.impl.BookDaoImpl;
import com.individual.enity.Book;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "AddBookServlet", value = "/addbookservlet")
public class AddBookServlet extends HttpServlet {
    @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 {
        //修改编码
        request.setCharacterEncoding("UTF-8");

        //获取表单数据
        Book book = new Book();
        Map<String, String[]> map = request.getParameterMap();

        try {
            BeanUtils.populate(book,map);

            //调用Dao中添加图书的方法
            BookDao bookDao = new BookDaoImpl();
            int row = bookDao.addBook(book);
            if (row != 0){
                //跳转到图书列表页
                response.sendRedirect("querybookservlet");
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}

** 2.创建 LoginServler**

import com.individual.dao.UserDao;
import com.individual.dao.impl.UserDaoImpl;
import com.individual.enity.User;

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

@WebServlet(name = "LoginServlet", value = "/loginservlet")
public class LoginServlet extends HttpServlet {
    @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 {

        //修改编码
        request.setCharacterEncoding("UTF-8");

        //接收表单传递的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //登陆界面的记住密码
        String remeber = request.getParameter("remeber");

        //构建成一个User的对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //调用Dao的登陆方法,验证能否登录
        UserDao userDao = new UserDaoImpl() ;
        User loginUser = userDao.login(user);

        if (loginUser == null){
            //登陆失败
            request.setAttribute("errmsg","账号或密码错误");
            request.getRequestDispatcher("index.jsp").forward(request,response);

        }else {
            //登陆成功
            if (remeber != null){
                //记住密码 -- 写Cookie
                        //账号
                Cookie cookie_username = new Cookie("username", username);
                cookie_username.setMaxAge(60*5);
                response.addCookie(cookie_username);

                        //密码
                Cookie cookie_password = new Cookie("password", password);
                cookie_password.setMaxAge(60*5);
                response.addCookie(cookie_password);

            }else {
                //删除密码 -- 删Cookie
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("username") || cookie.getName().equals("password")){
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }
            //创建session对象,保存用户的信息
            HttpSession session = request.getSession();
            session.setAttribute("loginUser",loginUser); //存入数据

            response.sendRedirect("querybookservlet");
        }

    }
}

** 3.创建 QueryBookServlet**

import com.individual.dao.BookDao;
import com.individual.dao.impl.BookDaoImpl;
import com.individual.enity.Book;

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

@WebServlet(name = "QueryBookServlet", value = "/querybookservlet")
public class QueryBookServlet extends HttpServlet {
    @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 {
        //查询所有图书信息
        BookDao bookDao = new BookDaoImpl();
        List<Book> allBooks = bookDao.getAllBooks();

        //转发到bookList.jsp 显示
        request.setAttribute("list",allBooks);
        request.getRequestDispatcher("bookList.jsp").forward(request,response);
    }
}

** 4.创建 RegisterServlet**

import com.individual.dao.UserDao;
import com.individual.dao.impl.UserDaoImpl;
import com.individual.enity.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "RegisterServlet", value = "/registerservlet")
public class RegisterServlet extends HttpServlet {
    @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 {
        //修改编码
        request.setCharacterEncoding("UTF-8");

        //获取表单元素(方式1:)
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
                //多选框 -- 不同
        String[] hobbies = request.getParameterValues("hobby");
        String hobbyStr = "" ;
        for (String hobby : hobbies) {
            hobbyStr += hobby + " " ;
        }

        String city = request.getParameter("city");
        String signature = request.getParameter("signature");

        //封装成User对象
        User user = new User(username, password, sex, hobbyStr, city, signature);

      /*

        //获取表单元素(方式2:BeanUtil (jar包:commons-logging-1.2.jar   commons-dbutils-1.7.jar))
            //封装成User对象
        User user = new User();
        Map<String, String[]> map = request.getParameterMap(); //多个单选处理封装
            //多选框需要单独处理
        String[] hobbies = request.getParameterValues("hobby");
        String hobbyStr = "" ;
        for (String hobby : hobbies) {
            hobbyStr += hobby + " " ;
        }

        try {
            BeanUtils.populate(user,map);
            user.setHobby(hobbyStr); //封装进多个爱好选项
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        */

        //调用Dao中的注册方法
        UserDao userDao = new UserDaoImpl();
        int row = userDao.register(user);

        //跳转到登陆界面
        if (row != 0 ){
            response.sendRedirect("index.jsp");
        }else {
            response.sendRedirect("register.html");
        }

    }
}
   **  5. 创建 GetBookInfoByIdServlet**
import com.individual.dao.BookDao;
import com.individual.dao.impl.BookDaoImpl;
import com.individual.enity.Book;

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

@WebServlet(name = "GetBookInfoByIdServlet", value = "/getBookInfoById")
public class GetBookInfoByIdServlet extends HttpServlet {
    @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 {
       //修改编码
        request.setCharacterEncoding("UTF-8");

        //获取图书的id
        int id = Integer.parseInt(request.getParameter("id"));

        //根据图书的id,查询图书的信息
        BookDao bookDao = new BookDaoImpl();
        Book book = bookDao.getBookById(id);

        //跳转到图书修改页面
        request.setAttribute("book",book);
        request.getRequestDispatcher("updateBook.jsp").forward(request,response);
    }
}

** 6. 创建 UpateBookServlet**

import com.individual.dao.BookDao;
import com.individual.dao.impl.BookDaoImpl;
import com.individual.enity.Book;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "UpateBookServlet", value = "/uptBook")
public class UpateBookServlet extends HttpServlet {
    @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 {
        //修改编码
        request.setCharacterEncoding("UTF-8");

        //获取页面上的图书信息(图书信息修改后的)
        Map<String, String[]> map = request.getParameterMap();
        Book book = new Book();

        try {
            BeanUtils.populate(book,map);

            //调用dao,执行修改图书功能
            BookDao bookDao = new BookDaoImpl();
            int row = bookDao.uptBook(book);

            //调转回 图书列表页
            if (row != 0){
                response.sendRedirect("querybookservlet");
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}

** 7.创建 DeleteBookServlet**


import com.individual.dao.BookDao;
import com.individual.dao.impl.BookDaoImpl;

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

@WebServlet(name = "DeleteBookServlet", value = "/delBook")
public class DeleteBookServlet extends HttpServlet {
    @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 {
        //获取图书id
        int id = Integer.parseInt(request.getParameter("id"));
        //调用dao中的删除图书的方法
        BookDao bookDao = new BookDaoImpl();
        int row = bookDao.dalBook(id);

        //跳转回 列表页
        if (row != 0){
            response.sendRedirect("querybookservlet");
        }
    }
}

2. 创建dao文件夹并在dao下创建文件夹impl

** 1.在dao下创建interface文件 - BookDao**

import com.individual.enity.Book;

import java.util.List;

public interface BookDao {
    //查询所有图书
    List<Book> getAllBooks();

    //添加图书
    int addBook(Book book);

    //根据图书id,查询图书信息
    Book getBookById(int id);

    //修改图书
    int uptBook(Book book);

    //删除图书
    int dalBook(int id);
}

** 2.在dao下创建interface文件 - UserDao**

import com.individual.enity.User;

/*
    UserDao :
     数据存取对象 - 增删改查
*/
public interface UserDao {
    User login(User user) ;  //登陆方法

    int register(User user) ; //注册方法

}

** 3.在impl下创建Java文件 - BookDaoImpl**

import com.individual.dao.BookDao;
import com.individual.enity.Book;
import com.individual.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class BookDaoImpl implements BookDao {

    QueryRunner qr = new QueryRunner();

    @Override
    public List<Book> getAllBooks() {
        List<Book> list = null;
        String sql = "select * from t_book" ;
        try {
            list = qr.query(DBUtil.getConn(),sql,new BeanListHandler<>(Book.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int addBook(Book book) {
        int row = 0 ;
        String sql = "insert into t_book values(null,?,?,?)";
        try {
            row = qr.update(DBUtil.getConn(), sql, book.getBookname(), book.getPrice(), book.getAuthor());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return row;
    }

    @Override
    public Book getBookById(int id) {
        Book book = null ;
        String sql = "select * from t_book where id = ?" ;
        try {
            book = qr.query(DBUtil.getConn(), sql, new BeanHandler<>(Book.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;
    }

    @Override
    public int uptBook(Book book) {
        int row = 0 ;
        String sql = "update t_book set bookname = ? , price = ? , author = ? where id = ?";
        try {
            row = qr.update(DBUtil.getConn(), sql, book.getBookname(), book.getPrice(), book.getAuthor(), book.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row ;
    }

    @Override
    public int dalBook(int id) {
        int row = 0;
        String sql = "delete from t_book where id = ?";
        try {
            row = qr.update(DBUtil.getConn(), sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}

** 4.在impl下创建Java文件 - UserDaoImpl**

import com.individual.dao.UserDao;
import com.individual.enity.User;
import com.individual.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    QueryRunner qr = new QueryRunner();

    //登录
    @Override
    public User login(User user) {
        User loginUser = null ;

        String sql = "select * from t_user where username = ? and password = ?" ;
        try {
            loginUser = qr.query(DBUtil.getConn(), sql, new BeanHandler<>(User.class), user.getUsername(), user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return loginUser;
    }

    //注册
    @Override
    public int register(User user) {
        int row = 0 ;

        String sql = "insert into t_user values(null,?,?,?,?,?,?)" ;
        try {
            row = qr.update(DBUtil.getConn(), sql, user.getUsername(), user.getPassword(), user.getSex(), user.getHobby(),
                    user.getCity(), user.getSignature());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}

3. 创建enity文件夹

** 1.创建Java文件 - Book**

/*
    使用Lombok实体类
 */

import lombok.Data;

@Data

public class Book {
   private int id ;
   private String bookname;
   private float price;
   private String author;

}

** 2.创建Java文件 - User**

/*
    实体类(JavaBean)
*/
public class User {
    private int id ;
    private String username ;
    private String password ;
    private String sex ;
    private String hobby ;
    private String city ;
    private String signature ;

    public User() {
    }

    public User(String username, String password, String sex, String hobby, String city, String signature) {
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.hobby = hobby;
        this.city = city;
        this.signature = signature;
    }

    public User(int id, String username, String password, String sex, String hobby, String city, String signature) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.hobby = hobby;
        this.city = city;
        this.signature = signature;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", sex='" + sex + '\'' +
                ", hobby='" + hobby + '\'' +
                ", city='" + city + '\'' +
                ", signature='" + signature + '\'' +
                '}';
    }
}

4. 创建util文件夹

** 1. 创建Java文件 - DBUtil**


import java.sql.*;

/*
    连接数据库的工具类
 */
public class DBUtil {

    //1.获取数据库连接
    public static Connection getConn(){
        Connection conn = null;
        //2.1 加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.2 获取连接
            String url = "jdbc:mysql://localhost:3306/jdbc?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
            String user = "root"; //数据库的用户名
            String password = "root"; //数据库的密码

            conn = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }
    //2.释放资源
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

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

5. 直接创建一个Test的Java类

** 1. 创建Java文件 - Test**

import com.individual.dao.BookDao;
import com.individual.dao.impl.BookDaoImpl;
import com.individual.dao.impl.UserDaoImpl;
import com.individual.enity.Book;
import com.individual.enity.User;

import java.util.List;
import java.util.Scanner;

public class Test {
    static Scanner sc = new Scanner(System.in) ;
    public static void main(String[] args) {

      //  testLogin(); //验证登录

      //  testRegister(); //验证注册

       //   testQueryBook(); //验证查询所有图书

        testAddBook(); //验证添加图书

    }

    private static void testAddBook() {
        Book book = new Book();
        book.setBookname("java");
        book.setPrice(20);
        book.setAuthor("曹操");

        BookDao bookDao = new BookDaoImpl();
        int row = bookDao.addBook(book);
        if (row != 0){
            System.out.println("图书添加成功");
        }
    }

    private static void testQueryBook() {
        BookDao bookDao = new BookDaoImpl();
        List<Book> books = bookDao.getAllBooks();
        for (Book book : books) {
            System.out.println(book);
        }
    }

    private static void testRegister() {
        System.out.println("请输入账号:");
        String username = sc.next();
        System.out.println("请输入密码:");
        String password = sc.next();
        System.out.println("请输入性别:");
        String sex = sc.next();
        System.out.println("请输入爱好:");
        String hobby = sc.next();
        System.out.println("请输入城市:");
        String city = sc.next();
        System.out.println("请输入个性签名:");
        String signature = sc.next();

        //构建User对象
        User user = new User(username, password, sex, hobby, city, signature);

        //调用Dao的注册方法
        UserDaoImpl userDao = new UserDaoImpl();
        int row = userDao.register(user) ;
        if (row != 0){
            System.out.println("注册成功");
        }else {
            System.out.println("注册失败");
        }

    }

    private static void testLogin() {
            //验证登录
            System.out.println("请输入账号:");
            String username = sc.next();
            System.out.println("请输入密码:");
            String password = sc.next();

            User user = new User();
            user.setUsername("username");
            user.setPassword("password");

            UserDaoImpl userDao = new UserDaoImpl();
            User loginUser = userDao.login(user);

            if (loginUser == null){
                System.out.println("登录失败");
            }else {
                System.out.println("登陆成功");
            }
        }

}

---------------------------------------------------- 改进版 --------------------------------------------------

新增技术:使用 Filter过滤器 、数据库连接池

   ** Filter过滤器(访问路径过滤器、修改编码过滤器):**

访问路径过滤器:

在src下新建一个包,名为: filter

在这个包下创建名为: AuthorFilter 的Filter文件


import com.individual.enity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "AuthorFilter",urlPatterns = "/*")
public class AuthorFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        //可直接放行的资源路径
        String uris[] = {
                "/ch07/",
                "/ch07/index.jsp",
                "/ch07/loginservlet",
                "/ch07/addBook.jsp",
        };

        //有一些资源可直接放行(登录页、验证页、首页)
        String requestURI = request1.getRequestURI();
        if (checkURI(uris,requestURI)){
            chain.doFilter(request, response);
            return;
        }

        //判断用户是否登录
        HttpSession session = request1.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        if (loginUser != null){
            //已登录,放行
            chain.doFilter(request, response);
        }else {
            //未登录,重定向到登录页
            response1.sendRedirect("index.jsp");

        }

    }

    //验证哪些资源可直接放行
    public boolean checkURI(String uris[],String requestUri){
        boolean flag = false;
        for (String s : uris) {
            if (requestUri.equals(s)){
                flag = true;
            }
        }
        return flag;
    }

}

修改编码过滤器:

在filter包下创建名为: EncodingFilter 的Filter文件

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

@WebFilter(filterName = "EncodingFilter",urlPatterns = "/*")
public class EncodingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //修改编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        chain.doFilter(request, response);
    }
}

(此时就可以将controller包下servlet文件中的修改编码代码删除)

        ** **

** 数据库连接池**

在src下新建下图所示配置文件

在lib文件夹下新添druid-1.1.12.jar

在util包下新建Java文件 : DruidUtils

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {
    //Druid德鲁伊,据说是魔兽世界中的一个角色,森林女神
    public static DruidDataSource dataSource;//数据库连接池

    //1.初始化Druid连接池
    static {
        //第二种方式:使用软编码通过配置文件初始化
        try {
            Properties properties = new Properties();
            //通过类加载器加载配置文件
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(inputStream);
            //创建连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //2.获取连接
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();//从连接池中获取连接
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static DataSource getDataSource(){
        return dataSource;
    }

    //3.释放资源
    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        //释放resultSet
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //释放Statement
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //释放Connection
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

将dao包下的impl包中的BookDaoImpl文件改成:

import com.individual.dao.BookDao;
import com.individual.enity.Book;
import com.individual.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class BookDaoImpl implements BookDao {

    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    @Override
    public List<Book> getAllBooks() {
        List<Book> list = null;
        String sql = "select * from t_book" ;
        try {
            list = qr.query(sql,new BeanListHandler<>(Book.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public int addBook(Book book) {
        int row = 0 ;
        String sql = "insert into t_book values(null,?,?,?)";
        try {
            row = qr.update(sql, book.getBookname(), book.getPrice(), book.getAuthor());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return row;
    }

    @Override
    public Book getBookById(int id) {
        Book book = null ;
        String sql = "select * from t_book where id = ?" ;
        try {
            book = qr.query(sql, new BeanHandler<>(Book.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;
    }

    @Override
    public int uptBook(Book book) {
        int row = 0 ;
        String sql = "update t_book set bookname = ? , price = ? , author = ? where id = ?";
        try {
            row = qr.update(sql, book.getBookname(), book.getPrice(), book.getAuthor(), book.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row ;
    }

    @Override
    public int dalBook(int id) {
        int row = 0;
        String sql = "delete from t_book where id = ?";
        try {
            row = qr.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}

将dao包下的impl包中的UserDaoImpl文件改成:

import com.individual.dao.UserDao;
import com.individual.enity.User;
import com.individual.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    //登录
    @Override
    public User login(User user) {
        User loginUser = null ;

        String sql = "select * from t_user where username = ? and password = ?" ;
        try {
            loginUser = qr.query(sql, new BeanHandler<>(User.class), user.getUsername(), user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return loginUser;
    }

    //注册
    @Override
    public int register(User user) {
        int row = 0 ;

        String sql = "insert into t_user values(null,?,?,?,?,?,?)" ;
        try {
            row = qr.update(sql, user.getUsername(), user.getPassword(), user.getSex(), user.getHobby(),
                    user.getCity(), user.getSignature());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}

(此时,即可将util包中DBUtil文件删除)

标签: 数据库 sql java

本文转载自: https://blog.csdn.net/m0_65765653/article/details/127819157
版权归原作者 努力学代码的小白菜 所有, 如有侵权,请联系我们删除。

“JavaWeb阶段案例--简易版管理图书系统(增删改查)”的评论:

还没有评论