首先要创建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 selectbook(int pageIndex, int pageSize) throws Exception {
// 创建list集合存放book对象
List list = new ArrayList();
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 likebook(int category, String name,int pageIndex, int pageSize)
throws Exception {
// 创建list集合存放book对象
List list = new ArrayList();
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 selectcategory() throws Exception {
List list=new ArrayList();
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 selectbook(int pageIndex,int pageSize) throws Exception;
//查询Book表的记录数
public int getCount() throws Exception;
//按图书名称查询(分页)
public List 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 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
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
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
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
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
* 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
* 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
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
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
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
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);
}
}
}