书城后台管理系统-JavaWeb项目(初学者)

一、项目实现流程

将将整个项目分成三个模块:View、Controller、Model

View:用来处理前端界面。包括登录界面(login.jsp)、主页(index.jsp)、添加图书(book-add.jsp)、图书列表(book-list.jsp)、图书修改(删改)(book-modify.jsp)、信息提示(prompt.jsp)六个页面设计。

Controller:用来接收浏览器发送来的请求。包括登录(LoginCheckServlet)、保存(BookSaveServlet)、列表(BookListServlet)、删除(BookDeleteServlet)、查询(BookQueryServlet)、更新(BookUpdateServlet)。

Model:用来执行操作的模块,将结果返回给前端页面。

二、具体操作实现

1.数据库设计:建库建表

2.Web项目搭建

2.1导入需要的jar包

2.2创建book和user的dto和dao

package com.qfedu.bookmall.ms.dto;

public class Book {
    
    private String bookId;
    private String bookName;
    private String bookAuthor;
    private double bookPrice;
    private String bookImgPath;
    private String bookDesc;
    private int bookStock;
    private int bookType;

}
package com.qfedu.bookmall.ms.dao;

import com.qfedu.bookmall.ms.dto.Book;
import com.qfedu.bookmall.ms.utils.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 BookDAO {

    public int insertBook(Book book){
        int i = 0;
        try {
            String sql = "insert into books(book_id,book_name,book_author,book_price,book_img_path,book_desc,book_stcok,book_type) values(?,?,?,?,?,?,?,?)";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            //给SQL中的参数赋值
            Object[] params = {book.getBookId(),book.getBookName(),book.getBookAuthor(),book.getBookPrice(),book.getBookImgPath(),book.getBookDesc(),book.getBookStock(),book.getBookType()};
            i = queryRunner.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    public List<Book> selectBooks(){
        List<Book> bookList = null;
        try {
            String sql = "select book_id bookId,book_name bookName,book_author bookAuthor,book_price bookPrice,book_img_path bookImgPath,book_desc bookDesc,book_stcok bookStock,book_type bookType from books";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            bookList = queryRunner.query(sql, new BeanListHandler<Book>(Book.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return bookList;
    }

    public int deleteBook(String bookId){
        int i = 0;
        try {
            String sql = "delete from books where book_id=?";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            i = queryRunner.update(sql, bookId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    public Book selectBookByBookId(String bookId){
        Book book = null;
        try {
            String sql = "select book_id bookId,book_name bookName,book_author bookAuthor,book_price bookPrice,book_img_path bookImgPath,book_desc bookDesc,book_stcok bookStock,book_type bookType from books where book_id=?";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            book = queryRunner.query(sql, new BeanHandler<Book>(Book.class),bookId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return book;
    }

    public int updateBook(Book book){
        int i = 0;
        try {
            String sql = "update books set book_name=?,book_author=?,book_price=?,book_img_path=?,book_desc=?,book_stcok=?,book_type=? where book_id=?";
            QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
            Object[] params = {book.getBookName(),book.getBookAuthor(),book.getBookPrice(),book.getBookImgPath(),book.getBookDesc(),book.getBookStock(),book.getBookType(),book.getBookId()};
            i = queryRunner.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
}

2.3编写六个html前端界面

2.4编写UserService和BookService

package com.qfedu.bookmall.ms.service;

import com.qfedu.bookmall.ms.dao.UserDAO;
import com.qfedu.bookmall.ms.dto.User;

public class UserService {

    public User checkLogin(String userName, String userPwd){
        //1.根据userName查询管理员信息
        UserDAO userDAO = new UserDAO();
        User user = userDAO.selectUserByUserName(userName);
        //2.判断密码
        if(user != null && user.getUserPwd() .equals(userPwd)){
            return user;
        }else{
            return null;
        }
    }
    
}
package com.qfedu.bookmall.ms.service;

import com.qfedu.bookmall.ms.dao.BookDAO;
import com.qfedu.bookmall.ms.dto.Book;

import java.util.List;

public class BookService {

    private BookDAO bookDAO = new BookDAO();

    public boolean saveBook(Book book){
        int i = bookDAO.insertBook(book);
        return i>0?true:false;
    }

    public boolean deleteBook(String bookId){
        int i = bookDAO.deleteBook(bookId);
        return i>0?true:false;
    }

    public Book getBook(String bookId){
        Book book = bookDAO.selectBookByBookId(bookId);
        return book;
    }

    public boolean modifyBook(Book book){
        int i = bookDAO.updateBook(book);
        return i>0?true:false;
    }

    public List<Book> listBooks(){
        List<Book> bookList = bookDAO.selectBooks();
        return bookList;
    }

}

2.5 将html转换为jsp,且链接各网页实现功能

//login.jsp:
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login.html</title>
    <style type="text/css">
        body{
            margin: 0px;
            padding: 0px;
        }
        #login_header{
            width:100%;
            height:150px;
        }
        #login_content{ /* 更正拼写 */
            height:600px;
            background-color: aquamarine;
            position: relative;
            display: flex;
            justify-content: center; /* 新增:居中显示 */
            align-items: center; /* 新增:垂直居中 */
        }
        #login_div{
            position: absolute;
            right:400px;
            top:100px;
        }

        #login_table{
            width: 400px;
            height: 400px;
            background-color: aliceblue;
            border: 1px lightblue solid;
            border-radius: 5px;
            box-shadow: gray 3px 3px 4px;
        }
        .inputstyle{
            width:300px;
            height:30px;
            border:1px lightgray solid;
            border-radius: 3px;
        }
        .btnstyle{
            width:300px;
            height:30px;
            border:1px lightgray solid;
            border-radius: 3px;
            background-color: orange;
        }
        .btnstyle:hover{
            background-color: cornflowerblue;
        }

    </style>
</head>
<body>
<div id="login_header">
    <h3>在线书城后台管理系统-欢迎登录</h3>
</div>
<div id="login_content"> <!-- 更正ID名称 -->
    <div id="login_div"> <!-- 修正闭合标签 -->
        <form action="LoginCheckServlet" method="post">
            <table id="login_table"   cellpadding="0">
                <tr height="80px">
                    <td align="center">管理员登录</td>
                </tr>
                <tr height="40">
<%--                    如果登录失败显示提示信息--%>
                    <td>${tips}</td>
                </tr>
                <tr>
                    <td align="center">
                        <input type="text" name="userName" placeholder="管理员账号" class="inputstyle"/>
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <input type="password" name="userPwd" placeholder="管理员密码" class="inputstyle"/>
                    </td>
                </tr>
                <tr>
                    <td align="center">
                        <input type="text" placeholder="验证码" class="inputstyle" style="width:200px"/>
                        <img src="" width="80" height="30">
                    </td>
                </tr>
                <tr height="80px">
                    <td align="center">
                        <input type="submit" placeholder="登录" class="btnstyle"/>
                    </td>
                </tr>
            </table>
        </form>

    </div>
</div>
<div id="login_footer">
    <table>

    </table>
</div>

</body>
</html>
//index.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        body{
            padding: 0px;
            margin: 0px;
        }

        #container{
            width: 100%;
            height: 800px;
        }
    </style>
</head>
<body>
<table id="container"  cellpadding="0" >
    <tr height="120">
        <td colspan="2" style="background-color:rebeccapurple ">
            <label style="color: cornflowerblue;font-size:25px;font-family: 楷体; ">在线书城后台管理系统</label>
        </td>
    </tr>
    <tr>
        <td width="220"  valign="top" style="padding-top: 20px;padding-left: 20px;border-right: 1px lightcoral solid;" >
            图书信息管理
            <ul style="list-style: none">
                <li><a href="book-add.jsp" target="mainFrame">添加图书</a></li>
                <li><a href="BookListServlet" target="mainFrame">图书列表</a></li>

            </ul>
            订单管理
            <ul style="list-style: none">
                <li><a href="">订单维护</a></li>
                <li><a href="">订单列表</a></li>
            </ul>
        </td>
        <td>
            <iframe name="mainFrame" width="100%" height="800" frameborder="0"></iframe>
        </td>
    </tr>
</table>

</body>
</html>
//book-add.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>添加图书信息</h3>
<form action="BookSaveServlet" method="post" enctype="multipart/form-data">
    <p>图书ID <input type="text" name="bookId"/></p>
    <p>图书名称 <input type="text" name="bookName"/></p>
    <p>图书作者 <input type="text" name="bookAuthor"/></p>
    <p>图书价格 <input type="text" name="bookPrice"/></p>
    <p>图书封面 <input type="file" name="bookImg"/></p>
    <p>图书描述 <input type="text" name="bookDesc"/></p>
    <p>图书库存 <input type="text" name="bookStock"/></p>
    <p>图书类型 <input type="radio" name="bookType" value="1"/>原创</p>
    <input type="radio" name="bookType" value="2"/>翻译</p>
    <p> <input type="submit" value="提交"/></p>

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>图书信息列表</h3>
<table align="center" border="1" cellspacing="0">
    <tr>
        <th>编号</th>
        <th>封面</th>
        <th>名称</th>
        <th>作者</th>
        <th>价格</th>
        <th>库存</th>
        <th>描述</th>
        <th>类型</th>
        <th>操作</th>
    </tr>
    <c:forEach items="${bookList}" var="book">
        <tr>
            <td>${book.bookId}</td>
            <td><img src="${book.bookImgPath}" height="50"></td>
            <td>${book.bookName}</td>
            <td>${book.bookAuthor}</td>
            <td><fmt:formatNumber value="${book.bookPrice}" type="currency"/></td>
            <td>${book.bookStock}</td>
            <td>${book.bookDesc}</td>
            <td>
                <c:if test="${book.bookType==1}">原创</c:if>
                <c:if test="${book.bookType==2}">翻译</c:if>
            </td>
            <td>
                <a href="BookQueryServlet?bookId=${book.bookId}">修改</a>
                <a href="BookDeleteServlet?bookId=${book.bookId}"
                   onclick="javascript:return confirm('你确定删除吗?')">删除</a>
            </td>
        </tr>
    </c:forEach>

</table>
</body>
</html>
//book-modify.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h3>修改图书信息</h3>
<form action="BookUpdateServlet" method="post">
    <p>图书ID <input type="text" name="bookId" value="${book.bookId}"/></p>
    <p>图书名称 <input type="text" name="bookName" value="${book.bookName}"/></p>
    <p>图书作者 <input type="text" name="bookAuthor" value="${book.bookAuthor}"/></p>
    <p>图书价格 <input type="text" name="bookPrice" value="${book.bookPrice}"/></p>
    <p>图书封面
        <img src="${book.bookImgPath}" height="100"/>
        <input type="hidden" name="bookImgPath" value="${book.bookImgPath}"/>
    </p>
    <p>图书描述 <input type="text" name="bookDesc" value="${book.bookDesc}"/></p>
    <p>图书库存 <input type="text" name="bookStock" value="${book.bookStock}"/></p>
    <p>图书类型
        <c:if test="${book.bookType==1}">
            <input type="radio" name="bookType" value="1" checked/>原创
            <input type="radio" name="bookType" value="2" />翻译
        </c:if>
        <c:if test="${book.bookType==2}">
            <input type="radio" name="bookType" value="1" />原创
            <input type="radio" name="bookType" value="2" checked />翻译
        </c:if>
    </p>
    <p> <input type="submit" value="提交"/></p>

</form>
</body>
</html>
//prompt.jsp
login.jsp<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div style="text-align: center;margin-top: 150px">
        ${tips}
    </div>
</body>
</html>

2.6 servlet实现

package com.example.bookmall_ms.servlet;

import com.example.bookmall_ms.dto.User;
import com.example.bookmall_ms.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/LoginCheckServlet")
public class LoginCheckServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName=req.getParameter("userName");
        String userPwd=req.getParameter("userPwd");

        UserService userService=new UserService();
        User user =userService.checkLogin(userName,userPwd);

        if(user==null){
            req.setAttribute("tips","<label style='color:red'>账号密码错误,登陆失败! </label>");
            req.getRequestDispatcher("login.jsp").forward(req,resp);

        }else{
            HttpSession session =req.getSession();
            session.setAttribute("user",user);
            resp.sendRedirect("index.jsp");
        }

    }
}
package com.example.bookmall_ms.servlet;

import com.example.bookmall_ms.dto.Book;
import com.example.bookmall_ms.service.BookService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.IOException;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet("/BookSaveServlet")
@MultipartConfig
public class BookSaveServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookId=req.getParameter("bookId");
        String bookName=req.getParameter("bookName");
        String bookAuthor=req.getParameter("bookAuthor");
        double bookPrice= Double.parseDouble(req.getParameter("bookPrice"));
        String bookDesc=req.getParameter("bookDesc");
        int bookStock= Integer.parseInt(req.getParameter("bookStock"));
        int bookType= Integer.parseInt(req.getParameter("bookType"));

        Part bookImg =req.getPart("bookImg");
        String header =bookImg.getHeader("Content-Disposition");
        String ext =header.substring(header.lastIndexOf("."),header.lastIndexOf("\""));
        String fileName= UUID.randomUUID().toString()+ext;

        String dir = getServletContext().getRealPath("\\files");
        String savePath =dir + "\\" +fileName;

        bookImg.write(savePath);
        Book book=new Book(bookId,bookName,bookAuthor,bookPrice,"files/"+fileName,bookDesc,bookStock,bookType);
        BookService bookService=new BookService();
        boolean b=bookService.saveBook(book);

        String tips=b?"<label style='color:green'>添加图书成功!</label>":"<label style='color:red'>添加图书失败!</label>";
        req.setAttribute("tips",tips);
        req.getRequestDispatcher("prompt.jsp").forward(req,resp);

    }
}
package com.example.bookmall_ms.servlet;

import com.example.bookmall_ms.service.BookService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/BookDeleteServlet")

public class BookDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookId=req.getParameter("bookId");
        BookService bookService=new BookService();
        boolean b=bookService.deleteBook(bookId);
        String tips=b?"<label style='color:green'>图书删除成功!</label>":"<label style='color:red'>图书删除失败!</label>";
        req.setAttribute("tips",tips);
        req.getRequestDispatcher("prompt.jsp").forward(req,resp);
    }
}

 

package com.example.bookmall_ms.servlet;

import com.example.bookmall_ms.dto.Book;
import com.example.bookmall_ms.service.BookService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebServlet("/BookUpdateServlet")

public class BookUpdateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookId=req.getParameter("bookId");
        String bookName=req.getParameter("bookName");
        String bookAuthor=req.getParameter("bookAuthor");
        double bookPrice= Double.parseDouble(req.getParameter("bookPrice"));
        String bookImgPath=req.getParameter("bookImgPath");
        String bookDesc=req.getParameter("bookDesc");
        int bookStock= Integer.parseInt(req.getParameter("bookStock"));
        int bookType= Integer.parseInt(req.getParameter("bookType"));

        Book book =new Book(bookId,bookName,bookAuthor,bookPrice,bookImgPath,bookDesc,bookStock,bookType);
        BookService bookService=new BookService();
        boolean b=bookService.modifyBook(book);
        String tips=b?"<label style='color:green'>图书修改成功!</label>":"<label style='color:red'>图书修改失败!</label>";
        req.setAttribute("tips",tips);
        req.getRequestDispatcher("prompt.jsp").forward(req,resp);
    }
}
package com.example.bookmall_ms.servlet;

import com.example.bookmall_ms.dto.Book;
import com.example.bookmall_ms.service.BookService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/BookListServlet")

public class BookListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BookService bookService=new BookService();
        List<Book> bookList=bookService.listBooks();
        req.setAttribute("bookList",bookList);
        req.getRequestDispatcher("book-list.jsp").forward(req,resp);
    }
}

2.7 实现原理

1.login操作的实现原理

首先,login.jsp前端通过form表单的action操作,实现点击登录跳转页面到logincheckservlet中

其次,logincheckservlet通过req得到参数username和userpwd的值,调用userservice

第三,在userservice中,调用dao中的selectUserByUserName,如果用户不空,则返回用户

第四,如果用户不空,将用户存到session并且重定向到index.jsp页面

否则,转发到ogin.jsp,提示登陆失败

[JavaWeb完结撒花~]

  • 6
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值