1. 程式人生 > >JAVAWEB---簡單的圖書管理系統

JAVAWEB---簡單的圖書管理系統

效果圖

在這裡插入圖片描述

實現的功能:圖書的增加,刪除,修改。此處為了方便,資料庫使用虛擬資料庫,直接匯入。

主要掌握的知識點:JDBC技術,前端與後端的邏輯,三層架構MVC的瞭解。

下面是程式碼詳解:
在這裡插入圖片描述
前端:index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    //UTF-8編碼格式
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圖書管理系統</title>
</head>
<body>
<!--頁面跳轉的作用,連結顯示的是/V1/book.do-->
<jsp:forward page="/v1/book.do">
<jsp:param name="action" value="list"/>
</jsp:forward>
</body>
</html>

modify.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	pageContext.setAttribute("ctx", request.getContextPath());//獲取專案路徑
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>修改書本</title>
</head>
<body>

	<h1 align="center">修改書本</h1>
	<hr>
	<br>
	//表單提交方法:post,
	<form method="post" action="${ctx}/v1/book.do?action=modify-submit">
		<table width="400" border="1" align="center">
		//隱藏書的id
			<input type="hidden" name="id" value="${book.id }">
			<tr>
				<td>名稱</td>
				//正則表示式顯示書名
				<td><input type="text" name="name" value="${book.name }"></td>
			</tr>

			<tr>
				<td>價格</td>
				<td><input type="text" name="price" value="${book.price }"></td>
			</tr>

		</table>
		<!-- 表單按鈕 -->
		<p align="center">
			<input type="submit" value="確定" name="btOk">
		</p>
</body>
</html>

listbook.jsp

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

<%
	pageContext.setAttribute("ctx", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圖書管理系統</title>
</head>
<body>

	<h1 align="center">圖書管理系統</h1>

	<table width="800" border="1" align="center">
		<tr>
			<td>id</td>
			<td>書名</td>
			<td>價格</td>
			<td colspan="2">操作</td>
		</tr>

		<c:forEach items="${books}" var="book" varStatus="idx">

			<tr>
				<td>${book.id }</td>
				<td>${book.name}</td>
				<td>${book.price}</td>
				//超連結,跳轉到delete介面
				<td><a href="${ctx}/v1/book.do?action=delete&id=${book.id }">刪除</a></td>
				<td><a href="${ctx}/v1/book.do?action=modify&id=${book.id }">修改</a></td>
			</tr>
		</c:forEach>
	</table>
	<br>

	<p align="center">
		<a href="./addbook.jsp">增加書本</a><br>
	</p>

</body>
</html>

addbook.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%
	pageContext.setAttribute("ctx", request.getContextPath());  //獲取專案路徑
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>新增書本</title>
</head>
<body>

	<h1 align="center">新增書本</h1>
	<hr>
	<br>
	<form method="post" action="${ctx}/v1/book.do?action=add-submit">
		<table width="400" border="1" align="center">

			<tr>
				<td>名稱</td>
				<td><input type="text" name="name" /></td>
			</tr>

			<tr>
				<td>價格</td>
				<td><input type="text" name="price" /></td>
			</tr>

		</table>
		<p align="center">
			<input type="submit" value="確定" name="btOk">
		</p>
</body>
</html>

後端的程式碼:
(模擬三層架構)

com.model

package com.model;
public class Book {
	public int id;
	public String name;
	public double price;

	public Book(int id, String name, double price) {
		this.id = id;
		this.name = name;
		this.price = price;
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}}
package com.servlet;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.BookDao;
import com.model.Book;

public class BookController extends HttpServlet {
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf8"); // 解決亂碼問題
		response.setCharacterEncoding("utf8");
		String action = request.getParameter("action"); // 根據action轉向不同的程式處理
		if (action == null || "list".equals(action)) { // 列表顯示
			BookDao dao = new BookDao();
			List books = dao.getBooks();//list列表儲存
			request.setAttribute("books", books);
			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp");
			view.forward(request, response);
		} else if ("delete".equals(action)) { // 刪除
			int id = Integer.parseInt(request.getParameter("id"));
			BookDao dao = new BookDao();
			boolean success = dao.removeBook(id);
			response.sendRedirect("/libmgr/v1/book.do");
		} else if ("add-submit".equals(action)) { // 新增提交
			String name = request.getParameter("name");
			double price = Double.parseDouble(request.getParameter("price"));
			BookDao dao = new BookDao();
			boolean success = dao.addBook(name, price);
			response.sendRedirect("/libmgr/v1/book.do");
		} else if ("modify".equals(action)) { // 修改
			int id = Integer.parseInt(request.getParameter("id"));
			BookDao dao = new BookDao();
			Book book = dao.getBookById(id);
			request.setAttribute("book", book);
			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/jsp/modifybook.jsp");
			view.forward(request, response);
		} else if ("modify-submit".equals(action)) { // 修改提交
			int id = Integer.parseInt(request.getParameter("id"));
			String name = request.getParameter("name");
			double price = Double.parseDouble(request.getParameter("price"));
			Book book = new Book(id, name, price);
			BookDao dao = new BookDao();
			dao.modifyBook(book);
			response.sendRedirect("/libmgr/v1/book.do");

		}
	}

}

package com.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.model.Book;

public class BookDao {

//	String url = "jdbc:mysql://localhost:3306/booksdb?user=root&password=root&characterEncoding=utf8";
//	String driver = "com.mysql.jdbc.Driver";
	String driver = "org.sqlite.JDBC";
	String path=this.getClass().getClassLoader().getResource("/").getPath();
	String dbfile=path.substring(0,path.length()-9)+"/books.db";
	String url = "jdbc:sqlite:"+dbfile;

	public List getBooks() {
		List list = new ArrayList();
//		System.out.println(path);
//		System.out.println(dbfile);
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url);
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM books");
			while (rs.next()) {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				double price = rs.getDouble("price");
				Book book = new Book(id, name, price);
				list.add(book);
			}
			st.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	public boolean removeBook(int id) {
		boolean success = false;

		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url);
			Statement st = conn.createStatement();
			success = st.execute("delete FROM books where id=" + id);
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return success;
	}

	public boolean addBook(String name, double price) {
		boolean success = false;
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url);
			Statement st = conn.createStatement();
			success = st.execute("insert into books(name,price) values('" + name + "'," + price + ")");
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return success;
	}
	
	public Book getBookById(int id) {
		Book book =null;
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url);
			Statement st = conn.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM books where id="+id);
			while (rs.next()) {
				int bid = rs.getInt("id");
				String name = rs.getString("name");
				double price = rs.getDouble("price");
				book = new Book(bid, name, price);
				
			}
			st.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return book;
	}
	
	public boolean modifyBook(Book book) {
		boolean success = false;
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url);
			PreparedStatement st = conn.prepareStatement("update books set name=? , price=? where id=?");
			st.setString(1, book.name);
			st.setDouble(2, book.price);
			st.setInt(3, book.id);
			success = st.execute();
			st.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return success;
	}

}