基本思路即为findAllBook(),很简单
主要代码如下:
dao:
public List getAllBook() throws SQLException {
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
return qr.query("select * from book",new BeanListHandler(Book.class));
}
service:
BookDao bd = new BookDaoImpl();
public List getAllBook() {
try {
return bd.getAllBook();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
controller:
package controller;
import pojo.Book;
import service.BookService;
import service.impl.BookServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class BookListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取表单数据
resp.setContentType("text/html;charset=UTF-8");
//调用业务逻辑
BookService bs = new BookServiceImpl();
List bookList = bs.getAllBook();
if (bookList!=null){
req.setAttribute("books",bookList);
//分发转向
req.getRequestDispatcher("/admin/products/list.jsp").forward(req,resp);
}
}
}
jsp:
<c:forEach items="${books}" var="book">
<tr onmouseover="this.style.backgroundColor = 'white'"
onmouseout="this.style.backgroundColor = '#F5FAFE';">
<td style="CURSOR: hand; HEIGHT: 22px" align="center"
width="23">${book.id}td>
<td style="CURSOR: hand; HEIGHT: 22px" align="center"
width="18%">${book.name}td>
<td style="CURSOR: hand; HEIGHT: 22px" align="center"
width="8%">${book.price}td>
<td style="CURSOR: hand; HEIGHT: 22px" align="center"
width="8%">${book.pnum}td>
<td style="CURSOR: hand; HEIGHT: 22px" align="center">${book.description}td>
<td align="center" style="HEIGHT: 22px" width="7%"><a
href="/servlet/findBookByIdServlet?id=${book.id}">
<img
src="${pageContext.request.contextPath}/admin/images/i_edit.gif"
border="0" style="CURSOR: hand"> a>
td>
<td align="center" style="HEIGHT: 22px" width="7%"><a
href="#">
<img
src="${pageContext.request.contextPath}/admin/images/i_del.gif"
width="16" height="16" border="0" style="CURSOR: hand">
a>
td>
tr>
c:forEach>
注意:添加成功的servlet里转发的是查询的servlet,数据才能更新
servlet:
package controller;
import pojo.Book;
import service.BookService;
import service.impl.BookServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AddBookServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取表单数据
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
String price = req.getParameter("price");
String number = req.getParameter("pnum");
String category = req.getParameter("category");
String description = req.getParameter("description");
Book book = new Book();
book.setName(name);
book.setPrice(Double.parseDouble(price));
book.setPnum(Integer.parseInt(number));
book.setCategory(category);
book.setDescription(description);
//调用业务逻辑
BookService bs = new BookServiceImpl();
bs.addBook(book);
//分发转向
req.getRequestDispatcher("/servlet/bookListServlet").forward(req,resp);
}
}
service:
public void addBook(Book book) {
try {
bd.addBook(book);
} catch (Exception e) {
e.printStackTrace();
}
}
dao:
public void addBook(Book book) throws Exception {
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
qr.update("insert INTO book(name,price,pnum,category,description) VALUES(?,?,?,?,?)",book.getName(),book.getPrice(),book.getPnum(),book.getCategory(),book.getDescription());
}
图示思路(数据先回显—–通过文本框的value ;再进行更新)
jsp:
//需要回显数据所以需要到数据库根据id查找书本信息
<td align="center" style="HEIGHT: 22px" width="7%"><a
href="/servlet/findBookByIdServlet?id=${book.id}">
servlet:
package controller;
import pojo.Book;
import service.BookService;
import service.impl.BookServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class FindBookByIdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
String id= req.getParameter("id");
BookService bs = new BookServiceImpl();
Book book = bs.findBookById(Integer.parseInt(id));
req.setAttribute("book",book);
req.getRequestDispatcher("/admin/products/edit.jsp").forward(req,resp);
}
}
service:
public Book findBookById(int id) {
try {
return bd.findBookById(id);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
dao:
public Book findBookById(int id) throws Exception {
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
return qr.query("select * from book where id = ?",new BeanHandler(Book.class),id);
}
jsp(查找完数据后再回显 类别使用的是select标签,需要js ;网页加载完成就需要判断完毕):
<tr>
//表单数据的回显---value
<td align="center" bgColor="#f5fafe" class="ta_01">商品名称:td>
<td class="ta_01" bgColor="#ffffff"><input type="text"
name="name" class="bg" value="${book.name}"/>td>
<td align="center" bgColor="#f5fafe" class="ta_01">商品价格:td>
<td class="ta_01" bgColor="#ffffff"><input type="text"
name="price" class="bg" value="${book.price}"/>td>
tr>
<tr>
<td align="center" bgColor="#f5fafe" class="ta_01">商品数量:td>
<td class="ta_01" bgColor="#ffffff"><input type="text"
name="pnum" class="bg" value="${book.pnum}"/>td>
<td align="center" bgColor="#f5fafe" class="ta_01">商品类别:td>
<td class="ta_01" bgColor="#ffffff"><select name="category"
id="category">
<option value="">--选择商品类加--option>
<option value="文学">文学option>
<option value="生活">生活option>
<option value="计算机">计算机option>
<option value="外语">外语option>
<option value="经营">经营option>
<option value="励志">励志option>
<option value="社科">社科option>
<option value="学术">学术option>
<option value="少儿">少儿option>
<option value="艺术">艺术option>
<option value="原版">原版option>
<option value="科技">科技option>
<option value="考试">考试option>
<option value="生活百科">生活百科option>
select>td>
tr>
<tr>
<td align="center" bgColor="#f5fafe" class="ta_01">商品图片:td>
<td class="ta_01" bgColor="#ffffff" colSpan="3"><input
type="file" name="upload" size="30" value="" />td>
tr>
<TR>
<TD class="ta_01" align="center" bgColor="#f5fafe">商品描述:TD>
<TD class="ta_01" bgColor="#ffffff" colSpan="3"><textarea
name="description" cols="30" rows="3" style="WIDTH: 96%">${book.description}textarea>
TD>
TR>
//select标签的回显
function setProductCategory(t) {
var category = document.getElementById("category");//得到下拉列表
var ops = category.options;//得到下拉列表中的所有option标签数组
for ( var i = 0; i < ops.length; i++) {
if (ops[i].value == t) {//循环判断哪一个option标签中的value值与t相等
ops[i].selected = true;//相等则把selected=selected
return;//结束循环
}
}
};
"setProductCategory('${book.category}')">//网页加载完毕就要判断完
修改数据库信息(因为要根据id修改数据,所以在jsp中写一个隐藏按钮,传id到servlet):
edit.jsp
type="hidden" name="id" value="${book.id}">
servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理表单数据
req.setCharacterEncoding("UTF-8");
String id = req.getParameter("id");
String name = req.getParameter("name");
String price = req.getParameter("price");
String pnum = req.getParameter("pnum");
String category = req.getParameter("category");
String description = req.getParameter("description");
Book book = new Book();
book.setId(Integer.parseInt(id));
book.setName(name);
book.setPrice(Double.parseDouble(price));
book.setPnum(Integer.parseInt(pnum));
book.setCategory(category);
book.setDescription(description);
//调用业务逻辑
BookService bs = new BookServiceImpl();
bs.updateBook(book);
//分发转向
req.getRequestDispatcher("/servlet/bookListServlet").forward(req,resp);
}
}
service:
public void updateBook(Book book) {
try {
bd.updateBookById(book);
} catch (Exception e) {
e.printStackTrace();
}
}
dao:
public void updateBookById(Book book) throws Exception {
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
qr.update("update book set name = ?,price = ?,pnum = ?,category = ?,description = ? where id=?",book.getName(),book.getPrice(),book.getPnum(),book.getCategory(),book.getDescription(),book.getId());
}
list.jsp:
//删除按钮的链接代码
"center" style="HEIGHT: 22px" width="7%">"javascript:deleteBook('${book.id}','${book.name}')">
"${pageContext.request.contextPath}/admin/images/i_del.gif"
width="16" height="16" border="0" style="CURSOR: hand">
//有关删除一本书的完整js的代码:
//提醒用户是否删除
function deleteBook(id,name) {
if(confirm("是否确定删除"+name)){
// alert(id);
location.href="/servlet/deleteBookServlet?id="+id;
}
}
DeleteServlet:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取表单对象
req.setCharacterEncoding("UTF-8");
String id = req.getParameter("id");
//调用业务逻辑
BookService bs = new BookServiceImpl();
bs.deleteBook(id);
//分发转向
req.getRequestDispatcher("/servlet/bookListServlet").forward(req,resp);
}
BookDaoImpl:
public void deleteBookById(String id) throws Exception {
QueryRunner qr= new QueryRunner(DBCPUtil.getDataSource()) ;
qr.update("delete from book where id = ?",id);
}
全选的js代码的实现
//全选、全不选功能的实现
function checkAll() {
//1.获取ckAll元素,并获取到它的状态
var flag = document.getElementById('ckAll').checked;
// alert(flag);
//2.获取ids元素组
var ids = document.getElementsByName('ids');
//3.循环遍历每个ids元素,并根据ckAll的状态为其状态赋值
for (var i=0;i
批量删除书本的思路:
1.要将复选框被选中的书本id传过去,value=${book.id}
2.通过js函数,用str=”“,和每个ids的值拼接传给servlet
3.qr.batch()
list.jsp:
function deleteAllBooks() {
//得到所有复选框元素
var ids = document.getElementsByName("ids");
var str="";
//循环得到选中的复选框的id
for (var i=0;iif(ids[i].checked){
str+="ids="+ids[i].value+"&";
}
}
str = str.substring(0,str.length-1);//[0,length-1)
// alert(str);
location.href="/servlet/deleteAllBooksServlet?"+str;//str=ids=1001&ids=1002&ids=1004
}
DeleteAllBooksServlet:
//批量删除
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取表单对象
String[] ids = req.getParameterValues("ids");
//调用业务逻辑
BookService bs = new BookServiceImpl();
bs.deleteAllBooks(ids);
//分发转向
req.getRequestDispatcher("/servlet/bookListServlet").forward(req,resp);
}
BookDaoImpl:
/*数组的3种初始化方式
1
Object[] oa = new Object[SIZE]; //声明和定义可分开
2
Object[] oa = new Object[]{obj1,obj2,obj3}; //同上
3
Object[] oa = {obj1,obj2,obj3}; //只能这样写 */
//批量删除商品
public void deleteAllbooks(String[] ids) throws Exception{
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
Object[][] params = new Object[ids.length][];//高维是行 即删除执行多少次
for (int i = 0;i<params.length;i++){
params[i] = new Object[]{ids[i]};//循环给每个数组中的元素赋值,一个?只用赋一个值;若多个即赋多个值
}
qr.batch("delete from book where id = ?",params);
}
list.jsp:
//点击查询,表单数据提交
form中action直接跳转到/servlet/searchBooksServlet
SearchBooksServlet:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
//获取表单数据
String id = req.getParameter("id");
String category = req.getParameter("category");
String name = req.getParameter("name");
String minprice = req.getParameter("minprice");
String maxprice = req.getParameter("maxprice");
//调用业务逻辑
BookService bs = new BookServiceImpl();
List bookList = bs.searchBooks(id, category,name,minprice,maxprice);
// System.out.println(bookList.size());
req.setAttribute("books",bookList);
//分发转向
req.getRequestDispatcher("/admin/products/list.jsp").forward(req,resp);
}
BookDaoImpl:
// 多条件查询商品
public List<Book> searchBooks(String id, String category, String name, String minprice, String maxprice) throws SQLException {
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
String sql = "select * from book where 1=1";
List list = new ArrayList();
if (!"".equals(id.trim())){
sql+=" and id like ?";//where id like %1002% 模糊查询
list.add("%"+id.trim()+"%");
}
if (!"".equals(category.trim())){
sql+=" and category = ?";
list.add(category.trim());
}
if (!"".equals(name.trim())){
sql+=" and name like ?";
list.add("%"+name.trim()+"%");
}
if (!"".equals(minprice.trim())){
sql+=" and price > ?";
list.add(minprice.trim());
}
if (!"".equals(maxprice.trim())){
sql+=" and price < ?";
list.add(maxprice.trim());
}
return qr.query(sql,new BeanListHandler<Book>(Book.class),list.toArray());
}
书本分页的大体思路:
1.将当前页currentPage和每页显示的数量pageSize传过去,通过sql语句limit的查询返回一个list显示书本信息
2.总共多少页,通过sql语句count的查询,Math.ceil(count*1.0/pageSize),向上取整
3.以上要返回currentPage,pageSize,list< book>,totalPage,所以封装为PageBean实体类
product_list.jsp:
//总页数 上一页和下一页的判断
<ul>
<li class="disablepage"><a href="/servlet/pageServlet?currentPage=${pb.currentPage==1?1:pb.currentPage-1}"><<上一页a>li>
<li>第${pb.currentPage}页/共${pb.totalPage}页li>
<li class="nextPage"><a href="/servlet/pageServlet?currentPage=${pb.currentPage==pb.totalPage?pb.totalPage:pb.currentPage+1}"><<下一页a>li>
ul>
//书本信息的显示
<div class="divlisttitle">
<a href="/servlet/bookDetailServlet?id=${book.id}">书名:${book.name}<br />售价:${book.price} a>
div>td>
BookServiceImpl:
public PageBean findBooksPage(int currentPage, int pageSize) {
//int count=? list book=?
try {
int count = bd.count();
//总共的页数 若一共10条数据则分4页 ;一共9条数据分3页
int totalPage =(int) Math.ceil(count*1.0/pageSize);//向上取整
List bookList = bd.findBooks(currentPage,pageSize);
PageBean pb = new PageBean();
pb.setTotalPage(totalPage);
pb.setCurrentPage(currentPage);
pb.setBookList(bookList);
pb.setCount(count);
pb.setPageSize(pageSize);
return pb;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
BookDaoImpl;
//获取数据的总条数
public int count() throws Exception{
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
long size = (Long) qr.query("select count(*) from book",new ScalarHandler(1));//返回类型为long
return (int)size;
}
//根据当前页数和每页的记录数 显示数据
public List findBooks(int currentPage, int pageSize) throws Exception {
QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
return qr.query("select * from book limit ?,?",new BeanListHandler(Book.class),(currentPage-1)*pageSize,pageSize);
}
直接把id传过去:
product_list.jsp:
<p>
<a href="/servlet/bookDetailServlet?id=${book.id}"><img src="" width="115" height="129"
border="0" /> a>
p>
BookDetailServlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取表单对象
String id = req.getParameter("id");
//调用业务逻辑
BookService bs = new BookServiceImpl();
Book book = bs.findBookById(Integer.parseInt(id));
req.setAttribute("book",book);
req.getRequestDispatcher("/product_info.jsp").forward(req,resp);
}
product_info.jsp:
<td style="padding:20px 5px 5px 5px"><img
src="images/miniicon3.gif" width="16" height="13" /><font
class="bookname"> ${book.name}font>
<hr />售价:<font color="#FF0000">¥:${book.price}font>
<hr /> 类别:${book.category}
<hr />
<p>
<b>内容简介:b>
p>${book.description}td>