基于Java Web的图书管理系统

目录

 4.3

4.4


1.系统简要概述

所用的思想是在MVC模式下进行开发,主要涉及到的内容有:JSP、javaBean、Servlet、JDBC、以及前端css、js,从具体实施来看主要涉及到的知识有:对jsp主要内置对象的熟练使用。例如,request请求、response响应、session会话、以及利用cookie来进行免登录,EL表达式,JSTL标签,Filter过滤器,Listener监视器,前端的灵活使用等。

2.系统主要用到的数据库表

admins(管理员) 管理员相关信息

Books(图书) 记录图书相关信息

Students(学生)表 记录学生相关信息

Borrows(借书) 记录借阅相关信息

3.主要功能

此次系统分为两个板块,管理员和用户。管理员主要进行用户和图书的增删改查,用户则进行借还操作。

下面简述两者主要功能及实现方法,具体可见后文详解。

管理员

增加学生、删除学生、查看学生、添加图书、修改图书、删除图书、查看图书

对学生的增删查,主要是在ManageStudent.Servlet里面进行。另外有专门处理学生的数据库类Student.Dao,首先增加和查看功能,直接利用前端提交的post请求,通过method字段在servlet里执行相对应的方法,将结果最终呈现在jsp页面中。至于删除的功能则是利用前端提交的get请求,将学生信息绑定在服务器前台,在后端通过request获取到相应数据,执行删除的方法。

对图书的增删改查类似以上机制,主要是在ManageBook.Servlet里面进行。同理也有Book.Dao,增删基本同添加学生一致。查看这里涉及到分页查看的机制,分页查看利用limit限制条件,对每次浏览的记录分条处理。通过后端每次传输的页值,将结果存储到session会话中,在jsp页面里,通过获取存储的对象输出到浏览器中。至于修改同查看一样,只不过这里,要将原先数据存到文本框内,需要通过get请求,将绑定的数据存储到会话中,然后重定向要修改的页面,中间借用EL表达式比较简洁。

用户:

查看图书、借书、借阅信息查看、还书、查看个人信息

当用户登录成功后,在左边功能框可查看所有图书信息,也可以查看具体类别的图书,这里主要是在userchoise.Servlet里面执行,当用户点击具体某类图书时,会将图书类别传输到服务器端,在servlet里面通过request获取类别,然后调用Book.Dao里面的方法将结果进行封装,在show.jsp页面里通过获取图书对象进行显示。每条图书信息后面附有借书操作功能,主要在Borrow.servlet里面进行,通过get机制将用户信息和图书信息上传到服务器,在servlet里面获取,然后利用Bean来声名对象,对借阅书籍进行更改,同时通过调用borrow.Dao,对图书信息数量进一步修改。

借阅信息的查看可直接在相应jsp里面,根据用户信息调用相应的Dao方法,来获取借阅书籍信息显示当浏览器上。在借阅信息里面可对图书进行归还操作,主要使用return.Servlet,在前端通过get机制,将学生信息和书籍信息上传到服务器端。在后端通过request获取,然后借用borrow.Dao,里面的方法对书籍数量进一步修改。查看个人信息比较见到,直接通过session会话,将事先绑定好的用户信息,直接读取,显示在相应页面中。

 3.1管理员功能

管理员主要管理学生和图书,在其项目里面有managestudent.servlet和managebook.servlet两个主要的servlet类。通过前端提供不同的请求来响应对应servlet里面的方法。

3.11登录

首先是管理员需要登录验证,判断数据库中是否有管理员账号相关信息。此次开发中,管理员账号为事先在数据库中录入,不支持注册和记住密码。管理员登录,需要请求adminlogin.servlet处理登录信息,如下(账号:admin 密码:admin):

图1- 1 管理员登录页面

若输入错误密码,则会提示密码错误重新登录(账号:admin 密码:123456):

图1- 2 管理员登录错误页面

3.12添加学生

添加学生功能,主要涉及到 student.dao(主要对学生进行数据库操纵,jdbc代码),student.bean(封装保存学生的基本信息),managestudent.servlet(用来后端操作控制添加学生信息的功能)以及addstusent.jsp(添加学生信息的前端页面)。添加信息的时候注意每项信息不能为空、以及添加的学生信息原数据库中是否有信息等需要在servlet里面做出判断。核心就是student.dao里面的连接数据库操纵语言,以及managestudent.servlet里面的对信息进行控制封装。如下:

图1-3 addstudent.jsp

3.13查看学生

查看学生功能是将数据库中的所有学生信息,展现在前端页面。这里主要涉及到studentDao、managestudent.servlet、student.javabean、showstudent.jsp等,在这里另外增加了一个分页查看的功能,主要思想就是在数据库里查询的时候将其分割,limit(beginpage,pagesize),然后通过查询的所有记录count/pagesize,得出总共的页数,然后在pageservlet里面,整理,最后输出到前端页面。

 3.14删除学生

管理员可以删除选中的学生,主要是利用前端绑定的机制,在get模式下,绑定用户的信息,通过前端传入的值,在后端进行相应的处理,在数据库中进行删除学生。所涉及到的类和前面几乎一致,不再重述。

3.15添加书籍

添加书籍类似添加学生,book.javabean(存有图书信息),managebook.Servlet(图书管理的servlet),以及对应的jsp页面.

 3.16查看书籍

管理员可查看所有图书信息。

 在show_book.jsp里面同时包含修改和删除图书的功能。两个方法对应不同的链接,跳转到相应的servlet中,在处理更改的时候需要用到重定向方法,将原先存到session中的数据,重定向到一个页面进行修改,同时该页面,要保留原有的信息,可以使用EL表达式来进行处理。

3.2用户端功能

3.2.1登录

用户登录页面同管理员登录页面一致,且在同一个jsp里,分两个form表单完成。在用户登录界面增加了注册、和记住密码的功能。首先看登录功能,用户输入账号和密码,前端将数据提交到后端的userloginServlet来进行处理,通过后端的处理与数据库中的结果作比较。验证登录是否成功,下图为登录成功界面。

在用户进行登录的时候有一个复选框,为记住密码的操作。当用户点击记住密码的时候,下次登录不用在输入账号密码,直接点击登录即可。这是利用cookie的机制,通过创建cookie,将账号信息保存到硬盘中。此次系统设计的cookie时间为三天。具体效果如下:

 

 

3.2.2注册 

注册功能同管理员添加学生一致,只不过这个注册会跳转到userloginsrvlet里面进行处理。结合数据库往里边添加数据,同时也会对,信息是否填写完整,以及原有数据库里面是否有数据做出判断。

3.2.3查询图书

 等用户登录成功后,即可看到左面功能栏里面的功能,最上面的就是查看所有图书功能,接下来的一系列则是根据图书类别进行查看图书,方便用户浏览,快速查找结果。里面的一些显示功能主要是,利用超链接的target,来将查询的结果输出到,showBook.jsp页面上。

3.2.4借阅书籍

每个书籍后面附有借书操作的功能,借阅实现的方法主要是,利用前端绑定机制,将用户的信息,和图书信息整合到一块,后端来进行获取。

当borrowservlet,接收到用户信息和图书信息后,通过studentBean,bookBean以及borrowBean,来对借阅功能进行封装处理,这时需要borrowdao来进行数据库的读写操作。

在这里设置每位用户最大借阅量为10本,所以在servlet里面,做出判断借阅量是否大于最大借阅书籍量。来响应用户是否还能继续借阅。若能借阅的话,则通过后台,处理Bean数据,用户借阅量发生变化,图书量也发生变化。

 3.2.5借阅信息查询

借阅信息查询这个页面中,可以显示所有借的图书信息,并且在这个页面附有还书的功能,借阅信息主要是利用BorrowServlet和BorrowDAO里面根据用户信息,来获取当前用户下共计的借阅量。

3.2.6还书

 还书对应的则是returnservlet,根据用户信息,以及图书信息,来做出合理的判断,在通过BorrowDao,里面的数据库操作对借书量,图书量数据上做出相应的改变。

3.2.7我的基本信息

在我的基本信息里面可以查看除密码以外的所有信息,包括当前借阅量,可借图书量等。具体实施为通过后台数据库将个人信息展现到页面上。

 4.代码部分

4.1 dao类

adminDao

package com.demo.dao;
import com.demo.javabean.*;
import java.sql.SQLException;

public class AdminDAO {
	DBAccess db ;
	public boolean valid(String username, String password) {
		boolean isValid = false;
		db=new DBAccess();
		if(db.createConn()) {
			try {
				String sql="select * from admins where admin=? and password=?";
				db.pre=db.getConn().prepareStatement(sql);
				db.pre.setString(1, username);
				db.pre.setString(2, password);
				db.setRs(db.pre.executeQuery());
				if(db.getRs().next()){
					isValid=true;
				}
			}catch (Exception e) {
				// TODO: handle exception
			}finally {
				db.closeRs();
				try {
					db.pre.close();
				} catch (SQLException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				db.closeConn();
			}
		}
		return isValid ;
	}
	public boolean isExist(String username) {
		boolean isExist = false;
		db = new DBAccess();
		if(db.createConn()) {
			try {
				String sql="select * from admins where admin=?";
				db.pre=db.getConn().prepareStatement(sql);
				db.pre.setString(1,username );
				db.setRs(db.pre.executeQuery());
				if(db.getRs().next()){
					isExist=true;
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			finally {
				db.closeRs();
				if(db.pre!=null){
					try {
						db.pre.close();
					} catch (Exception e2) {
						// TODO: handle exception
					}
				}
				db.closeConn();
			}
		}
		return isExist;
	}
}

 BookDao

package com.demo.dao;
import com.demo.javabean.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;


public class BookDAO  {
	DBAccess db;
	private Books book;
	public ArrayList<Books> getAllBooks() throws Exception{
		db=new DBAccess();

		//db.setSql("SELECT * FROM books");
		ArrayList<Books> books = new ArrayList<Books>();

		if(db.createConn()){
			//db.query(sql);
			String sql= "SELECT * FROM books";
			db.query(sql);


			while(db.getRs().next()){
				book = this.assemble(db.getRs());
				books.add(book);
			}
		}
		db.closeRs();
		db.closeStm();
		db.closeConn();
		return books;
	}


	public ArrayList<Books> getBooksByCategory(String category) throws Exception{//在这里进行分页判断

		ArrayList<Books> books = new ArrayList<Books>();
		DBAccess db=new DBAccess();
		java.sql.PreparedStatement pre = null;
		if(db.createConn()){
			//db.query(sql);
			String sql = "select * from books where category = ? ";
			pre=db.getConn().prepareStatement(sql);
			pre.setString(1, category);
			//pre.setInt(2, (page-1)*Students.PAGE_SIZE);
			//pre.setInt(3, Students.PAGE_SIZE);
			db.setRs(pre.executeQuery());
			while(db.getRs().next()){
				book = this.assemble(db.getRs());
				books.add(book);
			}
		}
		db.closeRs();
		db.closeStm();
		pre.close();
		db.closeConn();
		int a=books.size();
		System.out.println(a);
		return books;
	}


	public void addBook(String name,String author,String intro,String amount,String category) throws Exception{
		// boolean flag = false;
		DBAccess db = new DBAccess();
		if(db.createConn()){
			String sql = "insert into books(name,author,intro,amount,category) values('"+name+"','"+author+"','"+intro+"','"+amount+"','"+category+"')";
			db.update(sql);
			db.closeStm();
			db.closeConn();
		}
	}
	public boolean delbook(String name)throws Exception{//删除书籍
		DBAccess db = new DBAccess();
		boolean flag=false;
		if(db.createConn()){
			//db.setSql("delete from books where name = ?");
			String sql="delete from books where name = ?";
			db.pre=db.getConn().prepareStatement(sql);
			db.pre.setString(1, name);
			if(db.pre.executeUpdate()>0)flag=true;
			//String sql = "delete from books where name = '"+name+"'";
			//db.update(sql);
			//db.closeStm();
			//db.closeConn();
		}
		db.closeRs();
		db.closeStm();
		db.pre.close();
		db.closeConn();
		return flag;
	}
	public boolean isExist(String name) {
		boolean isExist = false;
		DBAccess db = new DBAccess();
		if(db.createConn()) {
			String sql = "select * from books where name='"+name+"'";
			db.query(sql);
			if(db.next()) {
				isExist = true;
			}
			db.closeRs();
			db.closeStm();
			db.closeConn();
		}
		return isExist;
	}




	public boolean updateBook(Books book) throws Exception{//借还更新 主要书籍数量
		boolean flag = false;
		DBAccess db=new DBAccess();
		String sql = "UPDATE books SET amount=? WHERE id=?";
		java.sql.PreparedStatement pre=null;
		if(db.createConn()){
			pre=db.getConn().prepareStatement(sql);

			//conn = OpenConnection.getConnection();
			// ps = conn.prepareStatement(sql_str);

			pre.setInt(1,book.getAmount());
			pre.setInt(2,book.getId());

			if(pre.executeUpdate() > 0) flag = true;
		}
		db.closeRs();
		db.closeStm();
		pre.close();
		db.closeConn();
		// this.release();
		// OpenConnection.closeConnection(conn);

		return flag;
	}
	public boolean updateBook2(Books book) throws Exception{//修改更新 修改图书信息
		boolean flag = false;
		DBAccess db=new DBAccess();
		//db.setSql("UPDATE books SET name=?,author=?,amount=?,category=? where id=?");

		if(db.createConn()){
			String sql="UPDATE books SET name=?,author=?,amount=?,category=? where id=?";
			db.pre=db.getConn().prepareStatement(sql);
			db.pre.setString(1, book.getName());
			db.pre.setString(2, book.getAuthor());
			db.pre.setInt(3, book.getAmount());
			db.pre.setString(4, book.getCategory());
			db.pre.setInt(5, book.getId());
			if(db.pre.executeUpdate() > 0) flag = true;
		}
		db.closeRs();
		db.closeStm();
		db.pre.close();
		db.closeConn();
		return flag;
	}



	public Books getBookById(int id) throws Exception{
		DBAccess db=new DBAccess();
		String sql = "SELECT * FROM books WHERE id = ?";
		java.sql.PreparedStatement pre=null;
		if(db.createConn()){
			pre=db.getConn().prepareStatement(sql);

			// conn = OpenConnection.getConnection();
			// ps = conn.prepareStatement(sql_str);
			pre.setInt(1,id);
			db.setRs(pre.executeQuery());

			if (db.getRs().next()) book = this.assemble(db.getRs());
		}
		db.closeRs();
		db.closeStm();
		pre.close();
		db.closeConn();
		//this.release();
		// OpenConnection.closeConnection(conn);
		return book;

	}


	public Books assemble(ResultSet rs) throws Exception{
		book = new Books();
		book.setId(rs.getInt("id"));
		book.setName(rs.getString("name"));
		book.setAuthor(rs.getString("author"));
		book.setIntro(rs.getString("intro"));
		book.setAmount(rs.getInt("amount"));
		book.setCategory(rs.getString("category"));
		return book;
	}
	public ArrayList<Books> findAll(Integer page){//分页查询信息
		DBAccess  db=new DBAccess();
		ArrayList<Books> list=new ArrayList<Books>();
		try {
			if(db.createConn()){
				String sql="select  * from books limit ?,? ";
				db.pre=db.getConn().prepareStatement(sql);
				db.pre.setInt(1, (page-1)*Students.PAGE_SIZE);
				db.pre.setInt(2, Students.PAGE_SIZE);
				db.setRs(db.pre.executeQuery());
				while(db.getRs().next()){
					Books book=new Books();
					book.setId(db.getRs().getInt("id"));
					book.setName(db.getRs().getString("name"));
					book.setAuthor(db.getRs().getString("author"));
					book.setCategory(db.getRs().getString("category"));
					book.setAmount(db.getRs().getInt("amount"));
					list.add(book);
				}
				db.closeRs();
				db.pre.close();
				db.closeConn();
			}
		} catch( SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	public ArrayList<Books> getBooksByCategory(String category,Integer page) throws Exception{//在这里进行分页判断(学生端)

		ArrayList<Books> books = new ArrayList<Books>();
		DBAccess db=new DBAccess();
		java.sql.PreparedStatement pre = null;
		if(db.createConn()){
			//db.query(sql);
			String sql = "select * from books where category = ? limit ?,?";
			pre=db.getConn().prepareStatement(sql);
			pre.setString(1, category);
			pre.setInt(2, (page-1)*Students.PAGE_SIZE);
			pre.setInt(3, Students.PAGE_SIZE);
			db.setRs(pre.executeQuery());
			while(db.getRs().next()){
				book = this.assemble(db.getRs());
				books.add(book);
			}
		}
		db.closeRs();
		db.closeStm();
		pre.close();
		db.closeConn();
		int a=books.size();
		System.out.println(a);
		return books;
	}
	public int countPage(String singal){//查询记录总数
		DBAccess  db=new DBAccess();
		int count=0;
		try {
			if(db.createConn()){
				String sql;
				if(!"1".equals(singal)){
					sql="select count(*) from books where category=?";
					db.pre=db.getConn().prepareStatement(sql);
					db.pre.setString(1, singal);
					db.setRs(db.pre.executeQuery());
				}
				else {
					sql="select count(*) from books";
					db.pre=db.getConn().prepareStatement(sql);
					db.setRs(db.pre.executeQuery());
				}
				if(db.getRs().next()){
					count=db.getRs().getInt(1);
				}
			}
		} catch( SQLException e) {
			e.printStackTrace();
		}
		finally {
			db.closeRs();
			try {
				if(db.pre!=null){
					db.pre.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
			db.closeConn();
		}
		return count;
	}
}

 BorrowDao

package com.demo.dao;

import com.demo.javabean.*;

import java.sql.ResultSet;
import java.util.ArrayList;

import com.demo.javabean.DBAccess;

public class BorrowDAO  {

    private Borrows borrow = null;
    public ArrayList<Borrows> getAllBorrows() throws Exception{
    DBAccess db=new DBAccess();
    java.sql.PreparedStatement pre=null;
       String sql = "SELECT * FROM borrows";
        ArrayList<Borrows> borrows = new ArrayList<Borrows>();
        //conn = OpenConnection.getConnection();
       // ps = conn.prepareStatement(sql_str);
        //rs = ps.executeQuery();
if(db.createConn()){
	pre=db.getConn().prepareStatement(sql);
	db.setRs(pre.executeQuery());
	//db.query(sql);
        while(db.getRs().next()) {
            borrow = this.assemble(db.getRs());
            borrows.add(borrow);
        }
}

        //this.release();
db.closeRs();
db.closeStm();
db.closeConn();
       // OpenConnection.closeConnection(conn);
        return borrows;
    }


    public ArrayList<Borrows> getBorrowsBySId(int s_id) throws Exception{
        ArrayList<Borrows> borrows = new ArrayList<Borrows>();
        DBAccess db=new DBAccess();
        java.sql.PreparedStatement pre=null;
       String sql = "SELECT * FROM borrows WHERE s_id = ?";
       if(db.createConn()){
    	   pre=db.getConn().prepareStatement(sql);
    	   pre.setInt(1, s_id);
    	   db.setRs(pre.executeQuery());
        while (db.getRs().next()){
            borrow = this.assemble(db.getRs());
            borrows.add(borrow);
        }
       }
       db.closeRs();
       db.closeStm();
       pre.close();
       db.closeConn();
        return borrows;
    }


    public boolean addBorrows(Borrows borrow) throws Exception{
        boolean flag = false;
        DBAccess db=new DBAccess();
        java.sql.PreparedStatement pre=null;
        String sql = "INSERT INTO borrows VALUES(?,?,?)";
        if(db.createConn()){
        pre=db.getConn().prepareStatement(sql);
        
       // conn = OpenConnection.getConnection();
       // ps = conn.prepareStatement(sql_str);
        pre.setInt(1,borrow.getS_id());
        pre.setInt(2,borrow.getB_id());
        pre.setInt(3,borrow.getAmount());
        if(pre.executeUpdate() > 0)  flag = true;
        }
        //this.release();
        db.closeRs();
        pre.close();
        db.closeConn();
        //OpenConnection.closeConnection(conn);

        return flag;

    }


    public boolean deleteBorrow(Borrows borrow) throws Exception{
        boolean flag = false;
        DBAccess db=new DBAccess();
        java.sql.PreparedStatement pre=null;
        String sql = "DELETE FROM borrows WHERE s_id = ? AND b_id = ? AND amount = ?";
        if(db.createConn()){
        pre=db.getConn().prepareStatement(sql);
        
        	
        //conn = OpenConnection.getConnection();
        //ps =conn.prepareStatement(sql_str);

        pre.setInt(1,borrow.getS_id());
        pre.setInt(2,borrow.getB_id());
        pre.setInt(3,borrow.getAmount());
        if(pre.executeUpdate() > 0) flag = true;
        }
        return flag;
    }



    public Borrows getBorrowById(int s_id, int b_id) throws Exception{
    	DBAccess db=new DBAccess();
        String sql = "SELECT * FROM borrows WHERE s_id = ? AND b_id = ?";
        java.sql.PreparedStatement pre=null;
        if(db.createConn()){
        pre=db.getConn().prepareStatement(sql);
        

        //conn = OpenConnection.getConnection();
        //ps = conn.prepareStatement(sql_str);
        pre.setInt(1,s_id);
        pre.setInt(2,b_id);

        //rs = ps.executeQuery();
        db.setRs(pre.executeQuery());
        if(db.getRs().next()) borrow = this.assemble(db.getRs());
        }
        db.closeRs();
        db.closeStm();
        pre.close();
        db.closeConn();
       // this.release();
       // OpenConnection.closeConnection(conn);
        return borrow;


    }


   public boolean updateBorrow(Borrows borrow) throws  Exception{
        boolean flag = false;
        DBAccess db=new DBAccess();
        String sql = "UPDATE borrows SET amount = ? WHERE s_id = ? AND b_id = ?";
        java.sql.PreparedStatement pre=null;
        if(db.createConn()){
        pre=db.getConn().prepareStatement(sql);
        
        //conn = OpenConnection.getConnection();
       // ps = conn.prepareStatement(sql_str);
        pre.setInt(1,borrow.getAmount());
        pre.setInt(2,borrow.getS_id());
        pre.setInt(3,borrow.getB_id());

        if(pre.executeUpdate() > 0) flag = true;
        }
        db.closeRs();
        db.closeStm();
        pre.close();
        db.closeConn();
        //this.release();
        //OpenConnection.closeConnection(conn);

        return flag;
    }



    public Borrows assemble(ResultSet rs) throws Exception{
        borrow = new Borrows();

        borrow.setS_id(rs.getInt("s_id"));
        borrow.setB_id(rs.getInt("b_id"));
        borrow.setAmount(rs.getInt("amount"));

        return borrow;
    }

}

 studentDao

package com.demo.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.demo.javabean.*;

/**
*@author:FQX
*@version:2022年3月28日下午7:43:34
*类说明
*/
public class StudentDAO {
	DBAccess db;
	public boolean valid(String username, String password) {
		boolean isValid = false;
		//DBAccess db = new DBAccess();
		db = new DBAccess();
		if(db.createConn()) {
			//String sql = "select * from students where user='"+username+"' and password='"+password+"'";
			//db.setSql("select * from students where user='"+username+"' and password='"+password+"'");
			String sql="select * from students where user= ? and password= ?";
			try {											//这里引用prepareStatement是为了防止SQL注入
				db.pre=db.getConn().prepareStatement(sql);
				db.pre.setString(1, username);
				db.pre.setString(2, password);
				db.setRs(db.pre.executeQuery());
				if(db.getRs().next()){
					isValid=true;
				}
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			finally {
				db.closeRs();
				if(db.pre!=null)
					try {
						db.pre.close();
					} catch (SQLException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				db.closeConn();
			}
			//db.query(sql);
			//		db.query(db.getSql());
			//		if(db.next()) {
			//			isValid = true;
			//		}
			//		db.closeRs();
			//		db.closeStm();
			//		db.closeConn();
		}
		return isValid ;
	}
	public boolean isExist(String username) {
		boolean isExist = false;
		db = new DBAccess();
		if(db.createConn()) {
			//String sql = "select * from students where user='"+username+"'";
			//db.setSql("select * from students where user='"+username+"'");
			String sql="select * from students where user=?";
			try {
				db.pre=db.getConn().prepareStatement(sql);
				db.pre.setString(1, username);
				db.setRs(db.pre.executeQuery());
				if(db.getRs().next()){
					isExist=true;
				}
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			finally {
				db.closeRs();
				if(db.pre!=null){
					try {
						db.pre.close();
					} catch (Exception e2) {
						// TODO: handle exception
					}
					db.closeConn();
				}
			}
			//db.query(sql);
			//			db.query(db.getSql());
			//			if(db.next()) {
			//				isExist = true;
			//			}
			//			db.closeRs();
			//			db.closeStm();
			//			db.closeConn();
		}
		return isExist;
	}
	public boolean add(Students student) throws Exception{//添加
		boolean flag = false;
		db=new DBAccess();
		String sql = "INSERT INTO students(user,password,department,grade,classes,email,amount) VALUES(?,?,?,?,?,?,?)";
		if(db.createConn()){
			db.pre=db.getConn().prepareStatement(sql);
			db.pre.setString(1,student.getUser());
			db. pre.setString(2,student.getPassword());
			db.pre.setString(3,student.getDepartment());
			db.pre.setString(4,student.getGrade());
			db. pre.setString(5,student.getClasses());
			db.pre.setString(6,student.getEmail());
			db.pre.setInt(7,student.getAmount());
			if(db.pre.executeUpdate() > 0) flag = true;
		}
		db.closeRs();
		db.closeStm();
		db.pre.close();
		db.closeConn();
		return flag;
	}

	public void del(String usename){//删除
		DBAccess db = new DBAccess();
		if(db.createConn()) {
			String sql = "delete from students where user = '"+usename+"'";
			db.update(sql);
			db.closeStm();
			db.closeConn();
		}
	}
	private Students student = null;
	public ArrayList<Students>getAllStudents() throws Exception{
		DBAccess db = new DBAccess();
		ArrayList<Students> students = new ArrayList<Students>();
		String sql = "SELECT * FROM students";
		if(db.createConn()){
			db.query(sql);
			while(db.getRs().next()){
				student = this.assemble(db.getRs());
				students.add(student);
			}
			db.closeStm();
			db.closeRs();
			db.closeConn();
		}
		return students;
	}
	public Students assemble(ResultSet rs) throws Exception{
		student = new Students();
		student.setId(rs.getInt("id"));
		student.setUser(rs.getString("user"));
		student.setPassword(rs.getString("password"));
		student.setDepartment(rs.getString("department"));
		student.setGrade(rs.getString("grade"));
		student.setClasses(rs.getString("classes"));
		student.setEmail(rs.getString("email"));
		student.setAmount(rs.getInt("amount"));
		return student;
	}

	public boolean delStudentByName(String user) throws Exception{//删除
		DBAccess db=new DBAccess();
		boolean flag = false;
		String sql="DELETE FROM students WHERE user = ?";
		if(db.createConn()){
			db.pre=db.getConn().prepareStatement(sql);
			db.pre.setString(1, user);
			if(db.pre.executeUpdate()>0)flag=true;
		}
		db.closeConn();
		db.closeStm();
		db.pre.close();
		db.closeRs();
		return flag;
	}

	public Students getStudentById(int id) throws Exception{
		DBAccess db=new DBAccess();
		String sql = "SELECT * FROM students WHERE id = ?";
		java.sql.PreparedStatement pre=null;
		if(db.createConn()){
			pre=db.getConn().prepareStatement(sql);
			pre.setInt(1, id);
			db.setRs(pre.executeQuery());
			//conn = OpenConnection.getConnection();
			//ps = conn.prepareStatement(sql_str);
			//ps.setInt(1,id);
			// rs = ps.executeQuery();
			if (db.getRs().next()) student = this.assemble(db.getRs());
		}
		db.closeRs();
		db.closeStm();
		pre.close();
		db.closeConn();
		//this.release();
		//OpenConnection.closeConnection(conn);
		return student;
	}
	public boolean updateStudent(Students student) throws Exception{
		boolean flag = false;
		DBAccess db=new DBAccess();
		String sql = "update students set amount = ? where id = ?";
		java.sql.PreparedStatement pre=null;
		if(db.createConn()){
			pre=db.getConn().prepareStatement(sql);

			//conn = OpenConnection.getConnection();
			// ps = conn.prepareStatement(sql_str);
			pre.setInt(1,student.getAmount());
			pre.setInt(2,student.getId());

			if(pre.executeUpdate() > 0) flag = true;
		}
		//this.release();
		//OpenConnection.closeConnection(conn);
		db.closeRs();
		pre.close();
		db.closeStm();
		db.closeConn();
		return flag;
	}
	public Students getStudentByName(String name) throws Exception{
		DBAccess  db=new DBAccess();
		String sql = "SELECT * FROM students WHERE user = ?";
		java.sql.PreparedStatement pre=null;
		if(db.createConn()){
			pre=db.getConn().prepareStatement(sql);
			pre.setString(1, name);
			db.setRs(pre.executeQuery());

			// conn = OpenConnection.getConnection();
			//ps = conn.prepareStatement(sql_str);
			//ps.setString(1,name);
			// rs = ps.executeQuery();

			if(db.getRs().next()) 
			student = this.assemble(db.getRs());
		}
		db.closeRs();
		db.closeStm();
		pre.close();
		db.closeConn();
		//this.release();
		// OpenConnection.closeConnection(conn);
		return student;
	}
	public ArrayList<Students> findAll(Integer page){//分页查询信息
		DBAccess  db=new DBAccess();
		ArrayList<Students> list=new ArrayList<Students>();
		
		try {
			if(db.createConn()){
				String sql="select  * from students limit ?,? ";
				db.pre=db.getConn().prepareStatement(sql);
				db.pre.setInt(1, (page-1)*Students.PAGE_SIZE);
				db.pre.setInt(2, Students.PAGE_SIZE);
				db.setRs(db.pre.executeQuery());
				while(db.getRs().next()){
					Students stu=new Students();
					stu.setUser(db.getRs().getString("user"));
					stu.setPassword(db.getRs().getString("password"));
					stu.setDepartment(db.getRs().getString("department"));
					stu.setGrade(db.getRs().getString("grade"));
					stu.setClasses(db.getRs().getString("classes"));
					stu.setEmail(db.getRs().getString("email"));
					stu.setAmount(db.getRs().getInt("amount"));
					list.add(stu);
				}
				db.closeRs();
				db.pre.close();
				db.closeConn();
			}
		} catch( SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	public int countPage(){//查询记录总数
		DBAccess  db=new DBAccess();
		int count=0;
		try {
			if(db.createConn()){
				String sql="select count(*) from students  ";
				db.pre=db.getConn().prepareStatement(sql);
				db.setRs(db.pre.executeQuery());
				if(db.getRs().next()){
					count=db.getRs().getInt(1);
				}
			}
		} catch( SQLException e) {
			e.printStackTrace();
		}
		finally {
			db.closeRs();
			try {
				if(db.pre!=null){
					db.pre.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
			db.closeConn();
		}
		return count;
	}
}

 4.2 Servlet类

userlojinServlet

package com.demo.servlet;
import com.demo.dao.AdminDAO;
import com.demo.dao.StudentDAO;
import com.demo.javabean.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;


public class UserLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = (String)request.getParameter("method");
		if(method==null) {
			PrintWriter out = response.getWriter();
			out.println("invalid request!");
		} else if(method.equals("login")) {
			try {
				Login(request, response);
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		else if(method.equals("register")) {
			try {
				Register(request, response);
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		else if(method.equals("logout")){
			Logout(request,response);
		}
	}
	//用户登录
	protected void Login(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//request.setCharacterEncoding("utf-8");
		//response.setCharacterEncoding("utf-8");
		//response.setContentType("text/html;charset=utf-8");
    	PrintWriter out = response.getWriter();
		String a_user = request.getParameter("user");
		String a_password = request.getParameter("password");
		System.out.println(a_user);
		String rem=request.getParameter("remember");
		HttpSession session = request.getSession();
		StudentDAO a_dao=new StudentDAO();
		if ("".equals(a_user) ||"".equals(a_password)) {
			//System.out.println("登录失败,账号或密码不能为空!");
			//response.sendRedirect("login.jsp");
			out.println("<script>" +
					"alert('登录失败,账号或密码不能为空!!!');" +
					"window.location.href = \"login.jsp\";" +
					"</script>");
			return;
		}
		else if(a_dao.isExist(a_user)){
			Students student=a_dao.getStudentByName(a_user);
			session.setAttribute("student", student);
			if(a_dao.valid(a_user, a_password)){
				session.setAttribute("a_user", a_user);
				user user=new user();
				session.setAttribute("user",user);
				if("1".equals(rem)){
					//创建2个Cookie
					Cookie namecookie=new Cookie("username", a_user);
					//设置Cookie的有效期为三天
					namecookie.setMaxAge(60*60*24*3);
					Cookie pwdcookie=new Cookie("password", a_password);
					pwdcookie.setMaxAge(60*60*24*3);
					response.addCookie(namecookie);
					response.addCookie(pwdcookie);
				}
				//response.sendRedirect(request.getContextPath()+"/user.jsp");
				//System.out.println("登录成功!");
				out.println("<script>" +
						"alert('登录成功!!!');" +
						"window.location.href = \"user.jsp\";" +
						"</script>");
			}
			else {
				//System.out.println("登录失败2,密码错误!");
				//response.sendRedirect(request.getContextPath()+"/login.jsp");
				out.println("<script>" +
						"alert('登录失败,密码错误!!!');" +
						"window.location.href = \"login.jsp\";" +
						"</script>");
			}
		}
		else {
			//System.out.println("登录失败3,用户名不存在!");
			//response.sendRedirect(request.getContextPath()+"/login.jsp");
			out.println("<script>" +
					"alert('登录失败,用户名不存在!!!');" +
					"window.location.href = \"login.jsp\";" +
					"</script>");
	}
	}
	//用户退出
	protected void Logout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("a_user");
		session.removeAttribute("user");
		response.sendRedirect("login.jsp");
	}
	//用户注册
	protected void Register(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
	{
		//request.setCharacterEncoding("utf-8");
		//response.setCharacterEncoding("utf-8");
		//response.setContentType("text/html;charset=utf-8");
    	PrintWriter out = response.getWriter();
		String user =  request.getParameter("user");
		String password = request.getParameter("password");
		String repwd= request.getParameter("repwd");
		String department =  request.getParameter("department");
		String grade =  request.getParameter("grade");
		String classes = request.getParameter("classes");
		String email =  request.getParameter("email");
		if ("".equals(user) ||"".equals(password) || "".equals(repwd) || !password.equals(repwd)||"".equals(department)||"".equals(grade)||"".equals(classes)||"".equals(email)) {
			//response.sendRedirect("reg.jsp");
			out.println("<script>" +
					"alert('注册失败,信息不全!!!');" +
					"window.location.href = \"reg.jsp\";" +
					"</script>");
			
			return;
		}else{
			Students student = null;
			StudentDAO a_dao = new StudentDAO();
			boolean isExist =a_dao.isExist(user);
			if(isExist){
				//System.out.println("'此学号已注册过,请重试!");
				//response.sendRedirect("reg.jsp");
				out.println("<script>" +
						"alert('此学号已注册过,请重试!!!');" +
						"window.location.href = \"reg.jsp\";" +
						"</script>");

			}else{
				student = new Students();
				student.setUser(user);
				student.setPassword(password);
				student.setDepartment(department);
				student.setGrade(grade);
				student.setClasses(classes);
				student.setEmail(email);
				student.setAmount(0);
				try {
					if(a_dao.add(student)){
						student = a_dao.getStudentByName(student.getUser());
						request.getSession().setAttribute("student",student);
						//System.out.println("注册成功,即将跳转到主界面!");
						//response.sendRedirect("login.jsp");
						out.println("<script>" +
								"alert('注册成功,即将跳转到主界面!!!');" +
								"window.location.href = \"login.jsp\";" +
								"</script>");
						return;
					}
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}

			}
		}
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//req.setCharacterEncoding("utf-8");
		this.doGet(req, resp);
	}

}

adminlojinServlet

package com.demo.servlet;

import java.io.*;
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.demo. dao.AdminDAO;
import com.demo.javabean.*;


public class AdminLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	String method = (String)req.getParameter("method");
    	if(method==null) {
			PrintWriter out = resp.getWriter();
			out.println("invalid request!");
		} else if(method.equals("login")) {
			Login(req, resp);
		}
    }
    //管理员登录
    protected void Login(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	//request.setCharacterEncoding("utf-8");
    	//response.setCharacterEncoding("utf-8");
		//response.setContentType("text/html;charset=utf-8");
    	PrintWriter out = response.getWriter();
        String a_user =request.getParameter("a_user");
        String a_password = request.getParameter("a_password");
        //HttpSession session = request.getSession();
        AdminDAO a_dao = new AdminDAO();
       //String admin = null;
        if ( a_user .equals("") ||a_password .equals("")) {
        	//System.out.println("登录失败");
			//response.sendRedirect("login.jsp");//重定向
        	out.println("<script>" +
					"alert('登录失败,用户名或密码不能为空!!!');" +
					"window.location.href = \"login.jsp\";" +
					"</script>");
			return;
		}
        boolean isValid =  a_dao.valid(a_user, a_password);
		if (isValid) {
			HttpSession session = request.getSession();
			session.setAttribute("a_user", a_user);
			out.println("<script>" +
					"alert('登录成功!!!');" +
					"window.location.href = \"admin.jsp\";" +
					"</script>");
			//response.sendRedirect("admin.jsp");//重定向
			return;
		}
		else {
			//System.out.println("登录失败");
			//response.sendRedirect("login.jsp");//重定向
			out.println("<script>" +
					"alert('登录失败,密码不正确!!!');" +
					"window.location.href = \"login.jsp\";" +
					"</script>");
			return;
		}
	}
//    protected void Logout(HttpServletRequest request,
//			HttpServletResponse response) throws ServletException, IOException {
//		HttpSession session = request.getSession();
//		session.removeAttribute("a_user");
//		response.sendRedirect("login.jsp");
//	}
//        


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

managebookservlet

package com.demo.servlet;

import com.demo.dao.BookDAO;
import com.demo.javabean.*;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
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 java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;


public class ManageBookServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//	HttpSession session=request.getSession();
//		if(session!=null&&session.getAttribute("a_user1")!=null){
//			String action = (String)request.getParameter("action");
//			if(action==null) {
//				PrintWriter out = response.getWriter();
//				out.println("invalid request!");
//			} else if(action.equals("addbook")) {
//				AddBook(request, response);
//			}
//			else if(action.equals("delbook")) {
//				DelBook(request, response);
//			}
//			else if(action.equals("updatebook")) {
//				UpdateBook(request, response);
//			}
//			else if(action.equals("update")) {
//				Update(request, response);
//			}
//		}
//		else {
//			response.sendRedirect("login.jsp");
//		}
		String action = (String)request.getParameter("action");
		if(action==null) {
		PrintWriter out = response.getWriter();
		out.println("invalid request!");
	} else if(action.equals("addbook")) {
		AddBook(request, response);
	}
	else if(action.equals("delbook")) {
		DelBook(request, response);
	}
	else if(action.equals("updatebook")) {
		UpdateBook(request, response);
	}
	else if(action.equals("update")) {
		Update(request, response);
	}
	}

	//更新图书
	private void Update(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException{
		// TODO 自动生成的方法存根
		//req.setCharacterEncoding("utf-8");
		//resp.setCharacterEncoding("utf-8");
		//resp.setContentType("text/html;charset=utf-8");
		Integer sid = Integer.parseInt(req.getParameter("sid"));
		BookDAO b_dao=new BookDAO();
		String page="";
		try {
			Books book=b_dao.getBookById(sid);
			req.setAttribute("book", book);
			req.getRequestDispatcher("admin/update_book.jsp").forward(req, resp);
		} catch (Exception e) {
			//page="error.jsp";
			//TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		//        finally{
		//        	page="admin/update_book.jsp";
		//        }
		//        req.getRequestDispatcher(page).forward(req, resp);
	}
	private void UpdateBook(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException {//修改图书信息
		// TODO 自动生成的方法存根
		//req.setCharacterEncoding("utf-8");
		//resp.setCharacterEncoding("utf-8");
		//resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
		String sid=req.getParameter("sid");
		String name=req.getParameter("name");
		String author=req.getParameter("author");
		String amount = req.getParameter("amount");
		String category = req.getParameter("category");
		BookDAO b_dao=new BookDAO();
		Books book=new Books();
		if(name != "" && author != "" && amount != "" && category != ""){
			book.setName(name);
			book.setAuthor(author);
			book.setAmount(Integer.parseInt(amount));
			book.setCategory(category);
			book.setId(Integer.parseInt(sid));
			try {
				if(b_dao.updateBook2(book)){
					//System.out.println("修改书籍成功!");
					//resp.sendRedirect("PageServlet.do?method=showBook");
					out.println("<script>alert('修改书籍成功!');" +
							"window.location.href = \"PageServlet.do?method=showBook\";" +
							"</script>");
					return;
				}
				else
					//System.out.println("修改书籍失败!内容不能为空");
					out.println("<script>alert('修改书籍失败!内容不能为空');" +
							"window.location.href = \"PageServlet.do?method=showBook\";" +
							"</script>");

			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}else
			//System.out.println("修改书籍失败!");
		//resp.sendRedirect("");
			out.println("<script>alert('修改书籍失败!');" +
					"window.location.href = \"PageServlet.do?method=showBook\";" +
					"</script>");

	}

	//删除图书
	private void DelBook(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
		// TODO 自动生成的方法存根
		//request.setCharacterEncoding("utf-8");
		//response.setCharacterEncoding("utf-8");
		//response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		String name=request.getParameter("name");
		BookDAO b_dao = new BookDAO();
		if(name!=null){
			try {
				if(b_dao.delbook(name)){
					//System.out.println("删除书籍成功!");
					//response.sendRedirect("PageServlet.do?method=showBook");
					//return;
					out.println("<script>alert('删除书籍成功!');" +
							"window.location.href = \"PageServlet.do?method=showBook\";" +
							"</script>");
					return;
				}
				else 
					//System.out.println("删除书籍失败!");
				//response.sendRedirect("admin/del_book.jsp");
					out.println("<script>alert('删除书籍失败!');" +
							"window.location.href = \"admin/del_book.jsp\";" +
							"</script>");

			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		else{
			//System.out.println("删除图书失败!无此图书");
			//response.sendRedirect("admin/del_book.jsp");
			out.println("<script>alert('删除书籍失败!');" +
					"window.location.href = \"admin/del_book.jsp\";" +
					"</script>");
		}
	}

	//添加图书
	private void AddBook(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException {
		// TODO 自动生成的方法存根
		//req.setCharacterEncoding("utf-8");
		//resp.setCharacterEncoding("utf-8");
		//resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
		String name = req.getParameter("name");
		String author = req.getParameter("author");
		String amount = req.getParameter("amount");
		String category = req.getParameter("category");
		String intro="暂未介绍";
		BookDAO b_dao = new BookDAO();
		Books book = null;
		if(name != "" && author != "" && amount != "" && category != ""){
			book = new Books();
			book.setName(name);
			book.setAuthor(author);
			book.setIntro("暂未介绍");
			book.setAmount(Integer.parseInt(amount));
			book.setCategory(category);
			//PrintWriter out = resp.getWriter();
			try {
				b_dao.addBook(name, author, intro, amount, category);
				//System.out.println("添加书籍成功!");
				//resp.sendRedirect("admin/reg_book.jsp");
				out.println("<script>alert('添加书籍成功!');" +
						"window.location.href = \"admin/reg_book.jsp\";" +
						"</script>");
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}else{
			//System.out.println("添加书籍失败!其他原因");
			//resp.sendRedirect("admin/reg_book.jsp");
			out.println("<script>alert('添加书籍失败!!其他原因');" +
					"window.location.href = \"admin/reg_book.jsp\";" +
					"</script>");
		}

	}


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//req.setCharacterEncoding("utf-8");
		doGet(req,resp);

	}
}

managestudentservlet

package com.demo.servlet;

import com.demo.dao.StudentDAO;
import com.demo.javabean.*;

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 java.io.IOException;
import java.io.PrintWriter;


public class ManageStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//    	HttpSession session=request.getSession();
//    	if(session!=null&&session.getAttribute("a_user1")!=null){
//    	String action = (String)request.getParameter("action");
//    	if(action==null) {
//			PrintWriter out = response.getWriter();
//			out.println("invalid request!");
//		} else if(action.equals("addstudent")) {
//			AddStudent(request, response);
//		}
//		else if(action.equals("delstudent")) {
//			DelStudent(request, response);
//		}
//		else if(action.equals("showstudent")){
//			ShowStudent(request,response);
//		}
//    	}
//    	else {
//			response.sendRedirect("login.jsp");
//		}
    	String action = (String)request.getParameter("action");
    	if(action==null) {
			PrintWriter out = response.getWriter();
			out.println("invalid request!");
		} else if(action.equals("addstudent")) {
			AddStudent(request, response);
		}
		else if(action.equals("delstudent")) {
			DelStudent(request, response);
		}
		else if(action.equals("showstudent")){
			ShowStudent(request,response);
		}
    }
        private void ShowStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
		// TODO 自动生成的方法存根
		//request.setCharacterEncoding("utf-8");
		String user=request.getParameter("user");
		StudentDAO studao=new StudentDAO();
		Students student=new Students();
		try {
			student=studao.getStudentByName(user);
			request.setAttribute("student", student);
			
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		request.getRequestDispatcher("admin/show_student.jsp").forward(request, response);
	}
		private void DelStudent(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException {
        	req.setCharacterEncoding("utf-8");
        	resp.setCharacterEncoding("utf-8");
        	resp.setContentType("text/html;charset=utf-8");
        	PrintWriter out=resp.getWriter();
        	String user=req.getParameter("user");
        	StudentDAO s_dao = new StudentDAO();
        	if(user!=null){
        		 System.out.println(user);
        		try {
					if(s_dao.delStudentByName(user)){
						// System.out.println("删除成功!");
						 //resp.sendRedirect("PageServlet.do?method=showStudent");
						out.println("<script>alert('删除成功!');"
						 +"window.location.href=\"PageServlet.do?method=showStudent\";"+"</script>");
						 return;
					}
					else
						//System.out.println("删除失败!");
					//resp.sendRedirect("admin/del_student.jsp");
						out.println("<script>alert('删除失败!');"
								 +"window.location.href=\"admin/del_student.jsp\";"+"</script>");
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
        	}
             else{
              	//System.out.println("删除失败,无此账号!");
              	//resp.sendRedirect("admin/del_student.jsp");
            	 out.println("<script>alert('删除失败,无此账号!');"
						 +"window.location.href=\"admin/del_student.jsp\";"+"</script>");
                }			
        }

		// TODO 自动生成的方法存根
		
		private void AddStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
		// TODO 自动生成的方法存根
		//req.setCharacterEncoding("utf-8");
		//resp.setCharacterEncoding("utf-8");
		//resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
        String user=req.getParameter("user");
        String password = req.getParameter("password");
        String relpwd=req.getParameter("relpwd");
        String department=req.getParameter("department");
        String grade = req.getParameter("grade");
        String classes=req.getParameter("classes");
        String email = req.getParameter("email");
        String admin=req.getParameter("admin");
        if ("".equals(user) || "".equals(password) ||"".equals(relpwd) || !password.equals(relpwd)||"".equals(department)||"".equals(grade)||"".equals(classes)||"".equals(email)) {
			//resp.sendRedirect("admin/add_student.jsp");
			//System.out.println("信息不全");
        	out.println("<script>alert('添加失败,信息不全!');" +
					"window.location.href = \"admin/add_student.jsp\";" +
					"</script>");
			return;
		}else{
        StudentDAO a_dao = new StudentDAO();
        Students student=new Students();
		boolean isExist =a_dao.isExist(user);
		if(isExist){
			//System.out.println("此学号已注册!");
			//resp.sendRedirect("admin/add_student.jsp");
			out.println("<script>alert('此学号已注册!');" +
					"window.location.href = \"admin/add_student.jsp\";" +
					"</script>");
		}
		else{
			 student = new Students();
	            student.setUser(user);
	            student.setPassword(password);
	            student.setDepartment(department);
	            student.setGrade(grade);
	            student.setClasses(classes);;
	            student.setEmail(email);
	            student.setAmount(0);
	            try {
					if(a_dao.add(student)){
						student = a_dao.getStudentByName(student.getUser());
					    req.getSession().setAttribute("student",student);
					//System.out.println("添加成功!");
					//resp.sendRedirect("");
					    out.println("<script>alert('添加成功!');" +
								"window.location.href = \"admin/add_student.jsp\";" +
								"</script>");
					return;
}
				} catch (Exception e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}

		}
		}
	}
		


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	//req.setCharacterEncoding("utf-8");
        doGet(req,resp);
    }
}

javaBean类

admin

package com.demo.javabean;

public class Admins {

    private int id;                     //定义管理员的id序号
    private String admin;               //登录账号
    private String password;            //密码
    private String realname;            //真实姓名
    private String phone;               //电话号码
    private String email;               //邮箱
    private String address;             //地址

    //获取管理员的id序号
    public int getId() {
        return id;
    }

    //设置管理员的id序号
    public void setId(int id) {
        this.id = id;
    }

    //获取管理员的账号
    public String getAdmin() {
        return admin;
    }

    //设置管理员的账号
    public void setAdmin(String admin) {
        this.admin = admin;
    }

    //获取管理员的密码
    public String getPassword() {
        return password;
    }

    //设置管理员的密码
    public void setPassword(String password) {
        this.password = password;
    }

    //获取管理员的真实姓名
    public String getRealname() {
        return realname;
    }

    //设置管理员的真实姓名
    public void setRealname(String realname) {
        this.realname = realname;
    }

    //获取管理员的电话
    public String getPhone() {
        return phone;
    }

    //设置管理员的电话号码
    public void setPhone(String phone) {
        this.phone = phone;
    }

    //获得管理员的邮箱地址
    public String getEmail() {
        return email;
    }

    //设置管理员的邮箱地址
    public void setEmail(String email) {
        this.email = email;
    }

    //获取管理员的地址
    public String getAddress() {
        return address;
    }

    //设置管理员的地址
    public void setAddress(String address) {
        this.address = address;
    }
}

student

package com.demo.javabean;

public class Students {
	public static final int PAGE_SIZE=5;
    private int id;
    private String user;
    private String password;
   private String department;
    private String grade;
    private String classes;
    private String email;
    private int amount;

    public int getId() {
        return id;
    }

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

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

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

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String getClasses() {
        return classes;
    }

    public void setClasses(String classes) {
        this.classes = classes;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }
}

book

package com.demo.javabean;

public class Books {
	private static final long serialVersionUID = 1L;
	public static final int PAGE_SIZE=5;
    private int id;
    private String name;
    private String author;
    private String intro;
    private int amount;
    private String category;

    //取得图书的id序号
    public int getId() {
        return id;
    }

    //设置图书的id序号
    public void setId(int id) {
        this.id = id;
    }

    //获取图书的名字
    public String getName() {
        return name;
    }

    //设置图书的名字
    public void setName(String name) {
        this.name = name;
    }

    //获取图书的作者
    public String getAuthor() {
        return author;
    }

    //设置图书的作者
    public void setAuthor(String author) {
        this.author = author;
    }

    //获取图书的简介
    public String getIntro() {
        return intro;
    }

    //设置图书的简介
    public void setIntro(String intro) {
        this.intro = intro;
    }

    //获取图书的数量
    public int getAmount() {
        return amount;
    }

    //设置图书的数量
    public void setAmount(int amount) {
        this.amount = amount;
    }

    //获取图书的类别
    public String getCategory() {
        return category;
    }

    //设置图书的类别
    public void setCategory(String category) {
        this.category = category;
    }
}

filter(过滤器类)

loginfilter

package com.demo.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginFilter implements Filter {//对登录进行验证过滤

	@Override
	public void destroy() {
		// TODO 自动生成的方法存根
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		// TODO 自动生成的方法存根
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse)resp;
		HttpSession session=request.getSession(false);
		if(session!=null&&session.getAttribute("a_user")!=null){
			//继续往下走
			chain.doFilter(request, response);
		}
		else {
			response.sendRedirect("login.jsp");
		}
		}
	

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO 自动生成的方法存根
		
	}

}

characterfilter

package com.demo.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CharacterFilter implements Filter {//对字符乱码问题进行过滤

	@Override
	public void destroy() {
		// TODO 自动生成的方法存根
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		// TODO 自动生成的方法存根
		HttpServletRequest request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse) resp;
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//继续执行
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO 自动生成的方法存根
		
	}

}

。。。因代码量较多,就不一一粘贴,有兴趣的友友可以交流。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年12月6日
下一篇 2023年12月6日

相关推荐

此站出售,如需请站内私信或者邮箱!