图书管理系统(增删改查带分页,上传)

首先要创建web项目,取名Book,创建分层,dao(impl),entuty,service,servlet,因为要用到分页,所以还有一个util;

创建分层之后,先写实体类,实体类包括下面这两张表的数据:
实体类对字符进行封装;
然后写basedao,就是连接数据库的工具类;
下一步就是创建bookdao接口的实现类,bookdaoimpl。bookdao接口中写要实现功能的方法,
在接口中 写入实现方法的sql语句:第一步,在页面查询出数据库中现有的数据:

public class BookDaoImpl extends BaseDao implements BookDao {


	@Test
	public void selectTest() throws Exception {
		
	}


	// 查询图书列表(分页)
	@Override
	public List<Book> selectbook(int pageIndex, int pageSize) throws Exception {
		// 创建list集合存放book对象
		List<Book> list = new ArrayList<Book>();
		String sql = "select * from book limit ?,?";
		Object[] obj = { pageIndex, pageSize };
		ResultSet rs = executeSelect(sql, obj);
		if (rs != null) {
			while (rs.next()) {
				// 创建book对象
				Book book = new Book();
				book.setBookid(rs.getInt("bookid"));
				book.setBookname(rs.getString("bookname"));
				book.setBookpicture(rs.getString("bookpicture"));
				book.setBookprice(rs.getDouble("bookprice"));
				book.setBookabout(rs.getString("bookabout"));
				book.setBookauthor(rs.getString("bookauthor"));
				book.setBookcategory(rs.getInt("bookcategory"));
				book.setBookdatatime(rs.getDate("bookdatetime"));
				list.add(book);
			}
		}
		return list;
	}


	// 查询book表中的记录数
	@Override
	public int getCount() throws Exception {
		int result = 0;
		String sql = "select count(*) as num from book";
		ResultSet rs = executeSelect(sql);
		if (rs != null) {
			if (rs.next()) {
				result = rs.getInt("num");
			}
			closeAll();
		}
		return result;
	}
// 按名称模糊查询(分页)
	@Override
	public List<Book> likebook(int category, String name,int pageIndex, int pageSize)
			throws Exception {
		// 创建list集合存放book对象
		List<Book> list = new ArrayList<Book>();
		StringBuffer sb=new StringBuffer("select * from book where 1=1");
		if(category!=0)
		{
			sb=sb.append(" and bookcategory='"+category+"' ");
		}
		if(name!="")
		{
			sb=sb.append(" and bookname like '%"+name+"%'");
		}
		sb=sb.append(" limit ?,?");
		Object[] obj = { pageIndex, pageSize };
		
		ResultSet rs = executeSelect(sb.toString(), obj);
		if (rs != null) {
			while (rs.next()) {
				// 创建book对象
				Book book = new Book();
				book.setBookid(rs.getInt("bookid"));
				book.setBookname(rs.getString("bookname"));
				book.setBookpicture(rs.getString("bookpicture"));
				book.setBookprice(rs.getDouble("bookprice"));
				book.setBookabout(rs.getString("bookabout"));
				book.setBookauthor(rs.getString("bookauthor"));
				book.setBookcategory(rs.getInt("bookcategory"));
				book.setBookdatatime(rs.getDate("bookdatetime"));
				list.add(book);
			}
		}
		return list;
	}


	@Override
	public int getselectCount(int category,String name) throws Exception {
		int result = 0;
		StringBuffer sb=new StringBuffer("select count(*) as num from book where 1=1 ");
		if(category!=0)
		{
			sb=sb.append(" and bookcategory='"+category+"' ");
		}
		if(name!="")
		{
			sb=sb.append(" and bookname like '%"+name+"%'");
		}
		ResultSet rs = executeSelect(sb.toString());
		if (rs != null) {
			if (rs.next()) {
				result = rs.getInt("num");
			}
			closeAll();
		}
		return result;
	}


	@Override
	public int deletebook(int id) throws Exception {
		String sql="delete from book where bookid='"+id+"'";
		int count = executeUpdate(sql);
		return count;
	}


	@Override
	public Book uploadbook(int id) throws Exception {
		Book book=new Book();
		String sql="select * from book where bookid='"+id+"'";
		ResultSet rs = executeSelect(sql);
		if(rs!=null)
		{
			if(rs.next())
			{
				book.setBookabout(rs.getString("bookabout"));
				book.setBookauthor(rs.getString("bookauthor"));
				book.setBookcategory(rs.getInt("bookcategory"));
				book.setBookdatatime(rs.getDate("bookdatetime"));
				book.setBookid(rs.getInt("bookid"));
				book.setBookname(rs.getString("bookname"));
				book.setBookpicture(rs.getString("bookpicture"));
				book.setBookprice(rs.getDouble("bookprice"));
			}
		}
		return book;
	}


	@Override
	public List<BookCategory> selectcategory() throws Exception {
		List<BookCategory> list=new ArrayList<BookCategory>();
		String sql="select * from BookCategory";
		ResultSet rs = executeSelect(sql);
		if(rs!=null)
		{
			while(rs.next())
			{
				BookCategory cate=new BookCategory();
				cate.setCateid(rs.getInt("cateid"));
				cate.setCatename(rs.getString("catename"));
				list.add(cate);
			}
		}
		return list;
	}
	//修改图书
	@Override
	public int bookupdate(Book book,int id) throws Exception {
		String sql="update book set bookname=?,bookcategory=?,bookprice=?,bookauthor=?,bookabout=?,bookdatetime=?,bookpicture=? where bookid=?";
		Object[] obj={book.getBookname(),book.getBookcategory(),book.getBookprice(),book.getBookauthor(),book.getBookabout(),book.getBookdatatime(),book.getBookpicture(),id};
		int count = executeUpdate(sql, obj);
		return count;
	}
	//添加图书
	@Override
	public int addbook(Book book) throws Exception {
		String sql="insert into book(bookname,bookcategory,bookprice,bookauthor,bookabout,bookdatetime,bookpicture) values(?,?,?,?,?,?,?)";
		Object [] obj={book.getBookname(),book.getBookcategory(),book.getBookprice(),book.getBookauthor(),book.getBookabout(),book.getBookdatatime(),book.getBookpicture()};
		int count = executeUpdate(sql, obj);
		return count;
	}
	


}
service:
public interface BookService {
	//查询图书列表(分页)
	public List<Book> selectbook(int pageIndex,int pageSize) throws Exception;
	//查询Book表的记录数
	public int getCount() throws Exception;
	//按图书名称查询(分页)
	public List<Book> likebook(int category,String name,int pageIndex, int pageSize) throws Exception;
	//查询Book表的记录数
	public int getselectCount(int category,String name) throws Exception;
	//删除book
	public int deletebook(int id) throws Exception;
	//修改book
	public Book uploadbook(int id) throws Exception;
	//查询book分类
	public List<BookCategory> selectcategory() throws Exception;
	//修改图书
	public int bookupdate(Book book,int id) throws Exception;
	//添加图书
	public int addbook(Book book) throws Exception;
}

service的实现类:

//创建BookDaoImpl对象,调用其方法
BookDao dao=new BookDaoImpl();
//查询图书带分页
@Override
public List<Book> selectbook(int pageIndex, int pageSize) throws Exception {
return dao.selectbook(pageIndex, pageSize);
}
//总记录数
@Override
public int getCount() throws Exception {
return dao.getCount();
}

@Override
public int deletebook(int id) throws Exception {
return dao.deletebook(id);
}
@Override
public Book uploadbook(int id) throws Exception {
return dao.uploadbook(id);
}
@Override
public List<BookCategory> selectcategory() throws Exception {
return dao.selectcategory();
}
@Override
public int bookupdate(Book book, int id) throws Exception {
return dao.bookupdate(book, id);
}
@Override
public int addbook(Book book) throws Exception {
return dao.addbook(book);
}
@Override
public List<Book> likebook(int category, String name, int pageIndex,
int pageSize) throws Exception {
return dao.likebook(category, name, pageIndex, pageSize);
}
@Override
public int getselectCount(int category, String name) throws Exception {
return dao.getselectCount(category, name);
}
}

最后就是servlet:

public class BookServlet extends HttpServlet {


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


doPost(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-type", "text/html;charset=UTF-8");
// 创建Service对象
BookService service = new BookServiceImpl();


try {
List<BookCategory> catelists = service.selectcategory();
request.setAttribute("catelists", catelists);
} catch (Exception e1) {
e1.printStackTrace();
}
String action = request.getParameter("action");
Page pages = new Page();




// 默认显示三条数据
int pageSize = 3;
pages.setPageSize(pageSize);
// 当前页
int myIndex;
String pageIndex = request.getParameter("pageIndex");
if (pageIndex != null) {
myIndex = Integer.parseInt(pageIndex);
} else {
myIndex = 1;
}
pages.setPageIndex(myIndex);
String select=request.getParameter("select");

if(select!=null&&select!="")
{

System.out.println("=====================");
String selectname = request.getParameter("selectname");
String selectcate=request.getParameter("bookcategoryid");
int mytotal;
try {
int totalpage = service.getselectCount(Integer.parseInt(selectcate), selectname);
if (totalpage % pageSize == 0) {
mytotal = totalpage / pageSize;
} else {
mytotal = totalpage / pageSize + 1;
}
pages.setTotalPages(mytotal);
List<Book> likebook = service.likebook(Integer.parseInt(selectcate), selectname,(pages.getPageIndex() - 1)
* pages.getPageSize(), pages.getPageSize());
pages.setBooklist(likebook);
request.setAttribute("selectname", selectname);
request.setAttribute("selectcate", selectcate);
request.setAttribute("Page", pages);
} catch (Exception e) {


}

}else
{

int mytotal;
try {
int totalpage = service.getCount();
if (totalpage % pageSize == 0) {
mytotal = totalpage / pageSize;
} else {
mytotal = totalpage / pageSize + 1;
}
pages.setTotalPages(mytotal);
List<Book> list = service.selectbook((pages.getPageIndex() - 1)
* pages.getPageSize(), pages.getPageSize());
pages.setBooklist(list);
request.setAttribute("Page", pages);


} catch (Exception e) {


}
}

if (action != null) {
// 删除book
if (action.equals("deletebook")) {
String id = request.getParameter("bookid");
try {
int deletebook = service.deletebook(Integer.parseInt(id));
if (deletebook > 0) {
System.out.println("删除成功!");
response.sendRedirect("/BookManager/BookServlet");
} else {
System.out.println("删除失败!");
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else if (action.equals("uploadbook")) {
String bookid = request.getParameter("bookid");
try {
List<BookCategory> catelist = service.selectcategory();
Book book = service.uploadbook(Integer.parseInt(bookid));
request.setAttribute("Book", book);
request.setAttribute("catelist", catelist);
request.getRequestDispatcher("/jsp/bookupdate.jsp")
.forward(request, response);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 修改图书
} else if (action.equals("updatebook")) {


String id = request.getParameter("id");
int bookid = Integer.parseInt(id);
Book book = new Book();
PrintWriter writer = response.getWriter();
String filedname = "";
boolean flag = ServletFileUpload.isMultipartContent(request);
if (flag) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> item = upload.parseRequest(request);
Iterator<FileItem> items = item.iterator();
while (items.hasNext()) {
FileItem fileitem = (FileItem) items.next();
if (fileitem.isFormField()) {
filedname = fileitem.getFieldName();
if (filedname.equals("bookName")) {
book.setBookname(fileitem
.getString("UTF-8"));
} else if (filedname.equals("bookauthor")) {
book.setBookauthor(fileitem
.getString("UTF-8"));
} else if (filedname.equals("bookcategoryid")) {
book.setBookcategory(Integer
.parseInt(fileitem
.getString("UTF-8")));
} else if (filedname.equals("bookPrice")) {
book.setBookprice(Float.parseFloat(fileitem
.getString("UTF-8")));
} else if (filedname.equals("bookdatetime")) {
String time = fileitem.getString("UTF-8");


SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
Date date;
try {
date = simpleDateFormat.parse(time);
book.setBookdatatime(date);
} catch (ParseException e) {
e.printStackTrace();
}


} else if (filedname.equals("bookabout")) {
book.setBookabout(fileitem
.getString("UTF-8"));
}
} else {
String tomactPath = this.getServletContext()
.getRealPath("/image/");
String fileName1 = fileitem.getName();
if (fileName1 == "") {
Book books = service.uploadbook(bookid);
book.setBookpicture(books.getBookpicture());
} else {
book.setBookpicture(fileName1);
}


if (fileName1 != null && !fileName1.equals("")) {
File fullFile = new File(fileitem.getName());
File saveFile = new File(tomactPath,
fullFile.getName());
try {
fileitem.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
tomactPath = fullFile.getName();
System.out.println("上传成功");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
int addbook = service.bookupdate(book, bookid);
if (addbook > 0) {
response.sendRedirect("/BookManager/BookServlet");
} else {
response.sendRedirect("BookManager/BookServlet?action=uploadbook");
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (action.equals("selectbookcatefory")) {


try {
List<BookCategory> catelist = service.selectcategory();
request.setAttribute("catelist", catelist);
request.getRequestDispatcher("/jsp/bookadd.jsp").forward(
request, response);
} catch (Exception e) {
e.printStackTrace();
}


} else if (action.equals("insertbook")) {
Book book = new Book();
PrintWriter writer = response.getWriter();
String filedname = "";
boolean flag = ServletFileUpload.isMultipartContent(request);
if (flag) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> item = upload.parseRequest(request);
Iterator<FileItem> items = item.iterator();
while (items.hasNext()) {
FileItem fileitem = (FileItem) items.next();
if (fileitem.isFormField()) {
filedname = fileitem.getFieldName();
if (filedname.equals("bookName")) {
book.setBookname(fileitem
.getString("UTF-8"));
} else if (filedname.equals("bookauthor")) {
book.setBookauthor(fileitem
.getString("UTF-8"));
} else if (filedname.equals("bookcategoryid")) {
book.setBookcategory(Integer
.parseInt(fileitem
.getString("UTF-8")));
} else if (filedname.equals("bookPrice")) {
book.setBookprice(Float.parseFloat(fileitem
.getString("UTF-8")));
} else if (filedname.equals("bookdatetime")) {
String time = fileitem.getString("UTF-8");


SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
Date date;
try {
date = simpleDateFormat.parse(time);
book.setBookdatatime(date);
} catch (ParseException e) {
e.printStackTrace();
}


} else if (filedname.equals("bookabout")) {
book.setBookabout(fileitem
.getString("UTF-8"));
}
} else {
String tomactPath = this.getServletContext()
.getRealPath("/image/");
String fileName1 = fileitem.getName();
System.out.println(fileName1);
book.setBookpicture(fileName1);
if (fileName1 != null && !fileName1.equals("")) {
File fullFile = new File(fileitem.getName());
File saveFile = new File(tomactPath,
fullFile.getName());
try {
fileitem.write(saveFile);
} catch (Exception e) {
e.printStackTrace();
}
tomactPath = fullFile.getName();
System.out.println("上传成功");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
try {
int addbook = service.addbook(book);
if (addbook > 0) {
response.sendRedirect("/BookManager/BookServlet");
} else {
response.sendRedirect("BookManager/BookServlet?action=selectbookcatefory");
}
} catch (Exception e) {
e.printStackTrace();
}
}else if(action.equals("filedown"))
{
//文件下载的根路径
String  path=getServletContext().getRealPath("/")+"image/";
//取到要下载的文件名称
String filename=request.getParameter("filename");
//读取文件
File  file=new File(path+filename);
//判断file是否为null
if(file!=null){
//设置相应的类型
//setContentType  使客户端浏览器调用不同的模块处理相应的数据
//文件下载所用的类型  application/x-msdownload或application/octet-stream
response.setContentType("application/x-msdownload");
//设置头信息  以复健的形式打开我们的下载文件  下载的时候文件名=filename
response.setHeader("Content-Disposition","attachment;filename=\""+filename+"\"");
//读取我们需要下载的文件
//获取文件输入流
InputStream   inputStream=new FileInputStream(file);
//获取文件返回的输出流
ServletOutputStream  sops=response.getOutputStream();
//循环将输入流信息写入到输出流中
//定义一个变量Byte[]  每次读取1024个字节
byte b[] =new byte[1024];
int n;
while((n=inputStream.read(b))!=-1){//如果不等于-1  循环读取
//写入到输出流中
sops.write(b, 0, n);
}
//关闭流  释放资源
sops.close();
inputStream.close();
}
}
} else {
request.getRequestDispatcher("/jsp/booklist.jsp").forward(request,
response);
}


}
}

  • 13
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
以下是一个基本的旅游路线的增删查带分页的 Java 示例: ```java public class TourRoute { private int id; private String name; private String description; private double price; private int days; // getters and setters } public class TourRouteDao { private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/tourdb"; private static final String USERNAME = "root"; private static final String PASSWORD = "password"; public List<TourRoute> getTourRoutes(int page, int pageSize) throws SQLException { List<TourRoute> routes = new ArrayList<>(); int offset = (page - 1) * pageSize; try (Connection conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); PreparedStatement stmt = conn.prepareStatement("SELECT * FROM tour_routes LIMIT ?, ?")) { stmt.setInt(1, offset); stmt.setInt(2, pageSize); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { TourRoute route = new TourRoute(); route.setId(rs.getInt("id")); route.setName(rs.getString("name")); route.setDescription(rs.getString("description")); route.setPrice(rs.getDouble("price")); route.setDays(rs.getInt("days")); routes.add(route); } } } return routes; } public void addTourRoute(TourRoute route) throws SQLException { try (Connection conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); PreparedStatement stmt = conn.prepareStatement("INSERT INTO tour_routes (name, description, price, days) VALUES (?, ?, ?, ?)")) { stmt.setString(1, route.getName()); stmt.setString(2, route.getDescription()); stmt.setDouble(3, route.getPrice()); stmt.setInt(4, route.getDays()); stmt.executeUpdate(); } } public void updateTourRoute(TourRoute route) throws SQLException { try (Connection conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); PreparedStatement stmt = conn.prepareStatement("UPDATE tour_routes SET name=?, description=?, price=?, days=? WHERE id=?")) { stmt.setString(1, route.getName()); stmt.setString(2, route.getDescription()); stmt.setDouble(3, route.getPrice()); stmt.setInt(4, route.getDays()); stmt.setInt(5, route.getId()); stmt.executeUpdate(); } } public void deleteTourRoute(int id) throws SQLException { try (Connection conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); PreparedStatement stmt = conn.prepareStatement("DELETE FROM tour_routes WHERE id=?")) { stmt.setInt(1, id); stmt.executeUpdate(); } } } ``` 以上是一个简单的 Java 类,用于实现旅游路线的增删查带分页。我们使用了 MySQL 数据库,以及 JDBC 驱动程序来连接数据库。其中,`TourRouteDao` 类包含了一些基本的方法,如 `getTourRoutes()` 方法用于查询旅游路线列表,`addTourRoute()` 方法用于添加新路线,`updateTourRoute()` 方法用于更新指定路线,`deleteTourRoute()` 方法用于删除指定路线。`getTourRoutes()` 方法使用了分页技术,将查询结果分为每页指定数量的项,并返回指定页数的结果列表。 需要注意的是,以上代码仅为示例,实际应用中需要根据业务需求进行适当的修和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值