天天看點

【Onlinebook2.0】基于MVC模式的JSP圖書管理系統,實作基本的增删改查。

這學期開了一門JSP課,老師布置了一個使用JSP完成增删改查的小作業。在圖書館和百度找的東西都不太全,廢了很大功夫。把自己寫的分享出來供新手學習使用。

程式結構:

【Onlinebook2.0】基于MVC模式的JSP圖書管理系統,實作基本的增删改查。

BookController.java

package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
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 dao.BookDao;
import domain.Book;
import util.DBCon;

public class BookController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		int arg = Integer.parseInt(request.getParameter("arg"));
		switch (arg) {
		case 1:
			this.findAllBooks(request, response);
			break;
		case 2:
			this.saveBooks(request, response);
			break;
		case 3:
			this.findById(request, response);
			break;
		case 4:
			this.delBooks(request, response);
			break;
		case 5:
			this.updateBooks(request, response);
			break;
		}
	}

	public void findAllBooks(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		BookDao bookDao = new BookDao();
		List list = bookDao.findAllbooks();
		request.setAttribute("booklist", list);
		RequestDispatcher rdt = request.getRequestDispatcher("showAllBooks.jsp");
		rdt.forward(request, response);
	}

	public void findById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			Long id = (long) Integer.parseInt(request.getParameter("id"));
			BookDao bookDao = new BookDao();
			Book book = bookDao.findById(id);
			request.setAttribute("bookId", book);
			RequestDispatcher rdt = request.getRequestDispatcher("updateBooks.jsp");
			rdt.forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void delBooks(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {

			int id = Integer.parseInt(request.getParameter("id"));
			BookDao bookDao = new BookDao();
			bookDao.delBooks(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.findAllBooks(request, response);
	}

	public void saveBooks(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = (String) request.getParameter("name");
		double price = Double.parseDouble(request.getParameter("price"));
		String author = (String) request.getParameter("author");
		String bookConcern = (String) request.getParameter("bookConcern");
		int counts = Integer.parseInt(request.getParameter("counts"));
		Book book = new Book();
		book.setName(name);
		book.setAuthor(author);
		book.setBookConcern(bookConcern);
		book.setPrice(price);
		book.setCounts(counts);
		BookDao bookDao = new BookDao();
		try {
			bookDao.saveBooks(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.findAllBooks(request, response);
	}

	public void updateBooks(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = (String) request.getParameter("name");
		double price = Double.parseDouble(request.getParameter("price"));
		String author = (String) request.getParameter("author");
		String bookConcern = (String) request.getParameter("bookConcern");
		int counts = Integer.parseInt(request.getParameter("counts"));
		int id = Integer.parseInt(request.getParameter("id"));
		Book book = new Book();
		book.setName(name);
		book.setAuthor(author);
		book.setBookConcern(bookConcern);
		book.setPrice(price);
		book.setCounts(counts);
		book.setId((long) id);
		BookDao bookDao = new BookDao();
		try {
			bookDao.updateBooks(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.findAllBooks(request, response);
	}

}
           

BookDao.java

package dao;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import java.sql.Statement;

import domain.Book;
import util.DBCon;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BookDao {
	private Connection conn;
	public List findAllbooks()
	{
		conn=DBCon.getConnection();
		String sql = "select * from books";
		List list = new ArrayList();
		try {
			PreparedStatement psmt =conn.prepareStatement(sql);
			ResultSet rs = psmt.executeQuery();
			while (rs.next()) {
				Book book = new Book();
				book.setId(rs.getLong(1));
				book.setName(rs.getString(2));
				book.setPrice(rs.getDouble(3));
				book.setAuthor(rs.getString(4));
				book.setBookConcern(rs.getString(5));
				book.setCounts(rs.getInt(6));
				list.add(book);
			}
			conn.commit();
			psmt.close();
			return list;
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(conn != null)
				try {
					conn.close();
				}catch (Exception e) {
					e.printStackTrace();
				}
		}	return list;
	}
	public Book findById(Long id) throws SQLException{
			Book book = null ;  
			conn=DBCon.getConnection();
        try {
			String sql = "SELECT name,price,author, bookConcern,counts FROM books WHERE id = "+id;
        	PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            if(rs.next()) {
            	book = new Book();
            	book.setId(id);
            	book.setName(rs.getString(1));
				book.setPrice(rs.getDouble(2));
				book.setAuthor(rs.getString(3));
				book.setBookConcern(rs.getString(4));
				book.setCounts(rs.getInt(5));
            }
            conn.commit();
    		pstmt.close();
    		return book;
        }
        catch (SQLException e) {
        	e.printStackTrace();
        } 
        return book;

    }
	public boolean saveBooks(Book book) throws Exception {
		conn = DBCon.getConnection();
		String listSQL= "insert into books(name,price,author,bookConcern,counts) values(?,?,?,?,?)";
		PreparedStatement pstmt =conn.prepareStatement(listSQL);
		try {
			pstmt.setString(1,book.getName());
			pstmt.setDouble(2, book.getPrice());
			pstmt.setString(3, book.getAuthor());
			pstmt.setString(4, book.getBookConcern());
			pstmt.setInt(5, book.getCounts());
			pstmt.executeUpdate();
			conn.commit();
		}catch (Exception e) {
			conn.rollback();
			e.printStackTrace();
		}finally {
			conn.close();
		}
		return false;
	}
	public boolean delBooks(int id) throws SQLException{	
		try {
			conn = DBCon.getConnection();
			String sql = "delete from books where id="+id;
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.executeUpdate();
			conn.commit();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{  
            // 關閉資料庫連接配接  
			conn.close();          
	}
		return false;
	}
	public boolean updateBooks(Book book) throws SQLException{
	
		try {
			conn = DBCon.getConnection();
			String sql = "update books set name=?,price=?,author=?,bookConcern=?,counts=? where id=?";
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,book.getName());
			pstmt.setDouble(2, book.getPrice());
			pstmt.setString(3, book.getAuthor());
			pstmt.setString(4, book.getBookConcern());
			pstmt.setInt(5, book.getCounts());
			pstmt.setLong(6, book.getId());
			pstmt.executeUpdate();
			conn.commit();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{  
            // 關閉資料庫連接配接  
			conn.close();          
	}
		return false;
	}
}
	


           

Book.java

package domain;

public class Book {
	private Long id;
	private String name;
	private double price;
	private String author;
	private String bookConcern;
	private int counts;
	public Long getId() {
		return id;
	}
	public void setId(Long 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;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getBookConcern() {
		return bookConcern;
	}
	public void setBookConcern(String bookConcern) {
		this.bookConcern = bookConcern;
	}
	public int getCounts() {
		return counts;
	}
	public void setCounts(int counts) {
		this.counts = counts;
	}
	
}
           

DBCon.java

package util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
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 java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import java.sql.Statement;
import java.sql.ResultSet;

public class DBCon {
	public static Connection getConnection() {
		String url = "jdbc:mysql://localhost:3306/db_book2.0?useSSL=false";
		String username = "root";
		String password = "root";
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			
		}catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection(url, username, password);
			conn.setAutoCommit(false);
			return conn;
		}
	catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
}

           

bookAdd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
<meta charset="utf-8">
</head>
<body>
	<form action="BookController?arg=2" method="post">
		<table>
			<tr>
				<td>圖書名稱:</td>
				<td><input type="text" name="name" /></td>
			</tr>
			<tr>
				<td>圖書價格:</td>
				<td><input type="text" name="price" /></td>
			</tr>
			<tr>
				<td>圖書作者</td>
				<td><input type="text" name="author" /></td>
			</tr>
			<tr>
				<td>出版社:</td>
				<td><input type="text" name="bookConcern" /></td>
			</tr>
			<tr>
				<td>存放數量:</td>
				<td><input type="text" name="counts" /></td>
			</tr>
			<tr>
				<td><input type="submit" name="submit" value="送出"></td>
				<td><input type="reset" value="重置"></td>
			</tr>
		</table>
	</form>
</body>
</html>
           

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="BookController?arg=1" target="_blank" rel="external nofollow" >showAllBook</a>
<a href="BookAdd.jsp" target="_blank" rel="external nofollow" >addBook</a>
</body>
</html>
           

showAllBooks.jsp

<%@ page language="java" import="java.util.*,domain.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table border=1>
		<tr>
			<td>圖書名稱</td>
			<td>圖書價格</td>
			<td>圖書作者</td>
			<td>出版社</td>
			<td>存放數量</td>
			<td>操作</td>
		</tr>
		<%
		request.setCharacterEncoding("UTF-8");
			List list = (List) request.getAttribute("booklist");
			Book book = new Book();
			for (int i = 0; i < list.size(); i++) {
				book = (Book) list.get(i);
		%>
		<tr>
			<td><%=book.getName()%></td>
			<td><%=book.getPrice()%></td>
			<td><%=book.getAuthor()%></td>
			<td><%=book.getBookConcern()%></td>
			<td><%=book.getCounts()%></td>
			<td><a href="BookController?id=<%=book.getId()%>&arg=3" target="_blank" rel="external nofollow" >修改</a> <a
				href="BookController?id=<%=book.getId()%>&arg=4" target="_blank" rel="external nofollow" >删除</a></td>

		</tr>
		<%
			}
		%>
	</table>
</body>
</html>
           

updateBooks.jsp

<%@ page language="java" import="java.util.*,domain.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="domain.Book"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		Book book = (Book) request.getAttribute("bookId");
	%>
	<form action="BookController?arg=5" method="post">
		<table border=1>
			 <input type="hidden" name="id" value="<%=book.getId()%>" >
			<tr>
				<td>圖書名稱</td>
				<td><input type="text" name="name" value="<%=book.getName()%>"></td>
			</tr>
		 <tr>
				<td>圖書價格</td>
				<td><input type="text" name="price"
					value="<%=book.getPrice()%>"></td>
			</tr>
			<tr>
				<td>圖書作者</td>
				<td><input type="text" name="author"
					value="<%=book.getAuthor()%>"></td>
			</tr>
			<tr>
				<td>出版社</td>
				<td><input type="text" name="bookConcern"
					value="<%=book.getBookConcern()%>"></td>
			</tr>
			<tr>
				<td>存放數量</td>
				<td><input type="text" name="counts"
					value="<%=book.getCounts()%>"></td>
			</tr>
			<tr>
				<td><input type="submit" name="submit" value="送出"></td>
				<td><input type="reset" value="重置"></td>
			</tr>
			</table>
	</form>
		
</body>
</html>
           

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>OnlineBooksMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
    <servlet>
    <servlet-name>BookController</servlet-name>
    <servlet-class>controller.BookController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>BookController</servlet-name>
    <url-pattern>/BookController</url-pattern>
  </servlet-mapping>   
</web-app>