Java Web实现简易图书管理系统
本文实例为大家分享了Java Web实现简易图书管理系统的具体代码,供大家参考,具体内容如下
前言
首先实现的是用户的登录注册,注册成功后自动跳转到图书列表页面,之后实现图书的增删改查功能。(菜鸡学习中,大佬勿喷)
一、运行环境
1.数据库:MySQL:5.7
2.Tomcat Apache 8.5
3.编译器:Eclipse 2020版
二、使用步骤
1.MySQL文件
User.sql:
* Navicat Premium Data Transfer Source Server : localhost_3306 Source Server Type : MySQL Source Server Version : 50723 Source Host : localhost:3306 Source Schema : library Target Server Type : MySQL Target Server Version : 50723 File Encoding : 65001 Date: 10/06/2021 17:59:30 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(10) NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (1, 'admin', 'admin'); INSERT INTO `user` VALUES (2, 'root', 'root'); INSERT INTO `user` VALUES (5, '123', '4596'); SET FOREIGN_KEY_CHECKS = 1;
booklist.sql:
/* Navicat MySQL Data Transfer Source Server : 121.36.6.154_3306 Source Server Version : 50720 Source Host : localhost:3306 Source Database : library Target Server Type : MYSQL Target Server Version : 50720 File Encoding : 65001 Date: 2021-06-22 16:05:51 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for booklist -- ---------------------------- DROP TABLE IF EXISTS `booklist`; CREATE TABLE `booklist` ( `id` int(10) NOT NULL AUTO_INCREMENT, `bookname` varchar(255) NOT NULL, `author` varchar(255) NOT NULL, `status` tinyint(255) NOT NULL, `price` double(10,0) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4;
2.项目的目录层次结构,导包
3.DBUtil类的创建
package com.qfnu.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtilTmp { public static void main(String[] args) { // 0.准备连接数据库的资源 String username = "root"; String password = "root"; // String url = "jdbc:mysql://127.0.0.1:3306/hellojdbc"; String url = "jdbc:mysql://localhost:3306/library"; String driver = "com.mysql.cj.jdbc.Driver"; Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; try { // 1.加载驱动 Class.forName(driver); // 2.获取连接 conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 7.释放资源,关闭连接 - 先申请的后释放 try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
4.Dao层的方法
userdao.java
package com.qfnu.Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.qfnu.entity.User; import com.qfnu.util.DBUtil; public class UserDao { public List<User> getAllUsers() throws SQLException { List<User> users = new ArrayList<User>(); // 获取连接 Connection conn = DBUtil.getConnection(); // 创建 sql 语句 String sql = "select * from user"; // 创建 PreparedStatement 对象 PreparedStatement pst = conn.prepareStatement(sql); // 执行 sql 语句,保存结果集 ResultSet rs = pst.executeQuery(); /** * 遍历结果集,将结果集中的每一条记录的每个字段值取出, * 封装为一个 user 对象,并把该 user 对象加入到 users 集合中。 */ while (rs.next()) { // 2.直接调用带参构造器 User user = new User(rs.getInt("id"), rs.getString("username"), rs.getString("password") ); users.add(user); } return users; } public void addUser(String username, String password) { List<User> users = new ArrayList<User>(); Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; try { // 获取连接 conn = DBUtil.getConnection(); // 创建 sql 语句 String sql = "insert into user(username,password) values(?,?)"; // 创建 PreparedStatement 对象 pst = conn.prepareStatement(sql); // 确定占位符的值 pst.setString(1, username); pst.setString(2, password); // 执行 sql 语句 int result = pst.executeUpdate(); if (result>0) { System.out.println("添加用户成功!!!"); } else { System.out.println("添加用户失败..."); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { DBUtil.release(conn, pst, rs); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
bookdao.java
package com.qfnu.Dao; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.qfnu.entity.Book; import com.qfnu.util.DBUtil; import com.qfnu.entity.Book; public class BookDao { public List<Book> getAllBooks() throws SQLException { List<Book> books = new ArrayList<Book>(); Connection conn = DBUtil.getConnection(); String sql = "select * from booklist"; PreparedStatement pst = conn.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while (rs.next()) { Book book = new Book(rs.getInt("id"), rs.getString("bookname"), rs.getString("author"), rs.getInt("status"), rs.getDouble("price")); books.add(book); } return books; } public void addBook(String bookname,String author,int status,double price ) { List<Book> books = new ArrayList<Book>(); Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; try { // 获取连接 conn = DBUtil.getConnection(); // 创建 sql 语句 String sql = "insert into booklist(bookname,author,status,price) values(?,?,?,?)"; // 创建 PreparedStatement 对象 pst = conn.prepareStatement(sql); // 确定占位符的值 pst.setString(1, bookname); pst.setString(2, author); pst.setInt(3, status); pst.setDouble(4, price); // 执行 sql 语句 int result = pst.executeUpdate(); if (result>0) { System.out.println("图书添加成功!"); } else { System.out.println("图书添加失败!"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { DBUtil.release(conn, pst, rs); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void delBook(int id) { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; try { // 获取连接 conn = DBUtil.getConnection(); // 创建 sql 语句 String sql = "DELETE FROM booklist WHERE id = ?"; // 创建 PreparedStatement 对象 pst = conn.prepareStatement(sql); // 确定占位符的值 pst.setInt(1, id); // 执行 sql 语句 int result = pst.executeUpdate(); if (result>0) { System.out.println("删除图书成功!!!"); } else { System.out.println("删除图书失败..."); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { DBUtil.release(conn, pst, rs); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public List<Book> SearchBook(String booksname) throws SQLException { // TODO Auto-generated method stub Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; Book book=new Book(); List<Book> books = new ArrayList<Book>(); String sql="select * from booklist where bookname=?"; try { conn = DBUtil.getConnection(); pst=conn.prepareStatement(sql); pst.setString(1, booksname); rs=pst.executeQuery(); if(rs.next()) { String bookname=rs.getString(2); String author=rs.getString(3); int status=rs.getInt(4); Double price=rs.getDouble(5); book = new Book(bookname,author,status,price); } books.add(book); DBUtil.release(conn, pst, rs); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return books; } public boolean UpdateBook(String bookname,String author,int status,double price) { Connection conn = null; PreparedStatement pst = null; ResultSet rs = null; String sql="update booklist set author=?,status=?,price=? where bookname=?"; try { conn = DBUtil.getConnection(); pst=conn.prepareStatement(sql); Book book = new Book(bookname,author,status,price); pst.setString(1, book.getAuthor()); pst.setInt(2, book.getStatus()); pst.setDouble(3, book.getPrice()); pst.setString(4, book.getBookname()); if(pst.executeUpdate()!=0) { return true; } DBUtil.release(conn, pst, rs); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }
5.封装到Service层
UserService.java
package com.qfnu.service; import java.sql.SQLException; import java.util.List; import com.qfnu.Dao.UserDao; import com.qfnu.entity.User; public class UserService { UserDao userDao = new UserDao(); public void addUser(String username, String password) { userDao.addUser(username, password); } public List<User> getAllUsers() throws SQLException{ return userDao.getAllUsers(); } }
BookService.java
package com.qfnu.service; import java.sql.SQLException; import java.util.List; import java.math.BigDecimal; import com.qfnu.entity.Book; import com.qfnu.Dao.BookDao; public class BookService { BookDao bookDao =new BookDao(); public List<Book> getAllBooks() throws SQLException{ return bookDao.getAllBooks(); } public void addBook(String bookname,String author,int status,double price) { bookDao.addBook(bookname, author,status,price); } public void delUser(int id) { bookDao.delBook(id); } public List<Book> SearchBook(String bookname) throws SQLException { return bookDao.SearchBook(bookname); } public boolean UpdateBook(String bookname,String author,int status,double price ) { boolean flag=bookDao.UpdateBook(bookname,author,status,price); if(flag==true) { return true; } return false; } }
6.在Controller层进行调用
LoginController.java (用户的登录)
package com.qfnu.controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.qfnu.entity.User; import com.qfnu.service.UserService; @WebServlet("/LoginController") public class LoginController extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户输入的用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); response.setContentType("text/html;charset=utf-8"); UserService userService = new UserService(); List<User> users = new ArrayList<User>(); PrintWriter out = response.getWriter(); String url = "login.jsp"; try { // 调用 service 层的 getAllUsers 方法来获取所有用户信息 users = userService.getAllUsers(); // 对 list 集合进行遍历 for (User user : users) { if (username.equals(user.getUsername())) { if (password.equals(user.getPassword())) { // 把后端的数据传递给前端展示:作用域 out.write("<script>alert('登录成功!')</script>"); request.getRequestDispatcher("BookListController").forward(request, response); break; } } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.write("<script>alert('登录失败!')</script>"); request.getRequestDispatcher(url).forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
RegisterCntroller.java (用户的注册功能)
package com.qfnu.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qfnu.service.UserService; @WebServlet("/RegisterController") public class RegisterController extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户输入的用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); UserService userService = new UserService(); userService.addUser(username, password); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<script>alert('注册成功!');window.location.href='login.jsp'</script>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
addBookController.java (图书的增加功能)
package com.qfnu.controller; import java.io.IOException; import java.io.PrintWriter; import java.math.BigDecimal; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qfnu.service.BookService; @WebServlet("/addBookController") public class addBookController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //设置相应的文本类型 response.setContentType("text/html;charset=utf-8"); BookService bookService = new BookService(); String bookname=request.getParameter("bookname"); String author=request.getParameter("author"); int status = Integer.parseInt(request.getParameter("status")); double price = Double.parseDouble(request.getParameter("price")); bookService.addBook(bookname, author, status, price); PrintWriter out = response.getWriter(); out.write("<script>alert('添加成功!');</script>"); request.getRequestDispatcher("BookListController").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
BookDelController.java (图书的删除)
package com.qfnu.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qfnu.service.BookService; @WebServlet("/BookDelController") public class BookDelController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idString = request.getParameter("id"); int id = Integer.parseInt(idString); BookService bookService = new BookService(); bookService.delUser(id); request.getRequestDispatcher("BookListController").forward(request, response); } }
updataBook.java (图书的更新功能)
package com.qfnu.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qfnu.service.BookService; @WebServlet("/updataBook") public class updataBookController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //设置相应的文本类型 response.setContentType("text/html;charset=utf-8"); BookService bookService = new BookService(); String bookname=request.getParameter("bookname"); String author =request.getParameter("author"); int status=Integer.parseInt(request.getParameter("status")); double price = Double.parseDouble(request.getParameter("price")); PrintWriter out = response.getWriter(); boolean flag = bookService.UpdateBook(bookname, author, status, price); if(flag==true) { out.print("<script>alert('更新成功!');</script>"); request.getRequestDispatcher("BookListController").forward(request, response); } else out.print("<script>alert('更新失败!');window.location.href='updataBook.jsp'</script>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
SearchBookController.java (图书的搜索功能)
```java package com.qfnu.controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.qfnu.entity.Book; import com.qfnu.service.BookService; @WebServlet("/SearchBook") public class SearchBookController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String bookname=request.getParameter("bookname"); BookService bookservice = new BookService(); try { List<Book> books = bookservice.SearchBook(bookname); request.setAttribute("books", books); request.getRequestDispatcher("searchBook.jsp").forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
7.总结
代码太多了,前端的东西就不放了,都是最基本的JSP文件,上述代码可能会有错,我还在不断学习中
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Java拦截器Interceptor和过滤器Filte的执行顺序和区别
本文主要介绍了Java拦截器Interceptor和过滤器Filte的执行顺序和区别,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2021-08-08用StopWatch优雅替代currentTimeMillis计算程序执行耗时
别再用System.currentTimeMillis()计算程序执行耗时了,拥抱StopWatch优雅来优雅的计算,代码更简洁效率更高,本文带你了解StopWatch的使用2021-09-09
最新评论