后台的数据结果。
今天案例出现频率很高的一个获取当前工程路径的代码:${pageContext.request.contextPath}指向了当前的工程路径
名称。比如:localhost:8080/day0610
这个形式的路径避免把绝对路径写死,便于后面的项目迁移。
比如,运用在前端的jQuery引入项目路径,可以写:
<script src='${pageContext.request.contextPath}/js/jquery1.8.3.js'>
</script>
这样子做的话,当以后前端部分的代码要迁移时,在正确迁移的情况下不必修改路径
一.分页查询——物理分页思路:
1.首先点击首页的"分页查询"链接,访问到DividePageServlet,get方式上传当前首页currPage=0的参数。2.创建一个PageBean 里面的成员属性有:
1)currPage:当前页面
2)pageSize:每页显示多少条记录
3)totalRecordNum:总记录数
4)totalPage:总页数
5)List<Product>:商品数据集合
3.接下来DividePageServlet的工作就是填充PageBean里面的属性。
1)新建一个PageBean对象。
2)由于分页查询的sql语句是使用关键字limit:select * from product limit [begin],[size];
begin:表示从哪一条查起
size:应该查多少条
3)可以算出:
begin = (currPage-1)*10:第1页 从0条开始;第2页从 从10条开始;第3页,从20条开始...
size = PageSize 可以写死final 10条;
4)上面的两个参数算完以后,
(1)获取总记录数totalRecordNum:
调用int count = PageService.getCount();
PageService调用PageDao.getCount();
使用sql语句select count(*) from product;
要使用new ScalarBeanHandler结果集,返回单一查询结果
(2)获取List<Product>集合:
调用List<Product> list = PageService.findAll(begin,size);
PageService调用PageDao.findAll(begin,size);
PageDao创建List<Product> findAll(begin,size)方法
方法里使用查询所有的sql语句,使用new BeanListHandler结果集,返回一个List<Product> list;
5)获取总页数totalPage
Math.ceil(totalRecordNum/size);
注意整形转换成Double型,再转回int型
6)至此,已经获取PageBean对象的所有属性。存放到request对象中,然后转发到商品分页页面product_divide.jsp页面
7)前端jsp展示分页的数据效果:
前面步骤已经存储了pageBean在session。接下来在dividePage_list.jsp中获取pageBean就能做了
jsp前端代码:
<p>
分页条: <a href='/day0610/DividePageServelt?currPage=1'>【首页】</a>
<c:if test="${pageBean.currPage!=1}">
<a href='/day0610/DividePageServelt?currPage=${pageBean.currPage-1}'>[上一页]</a>
</c:if>
<c:forEach begin="1" end="${pageBean.totalPageNum}" var="status">
<a href='/day0610/DividePageServelt?currPage=${status}'>[${status}]</a>
</c:forEach>
<c:if test="${pageBean.currPage!=pageBean.totalPageNum}">
<a href='/day0610/DividePageServelt?currPage=${pageBean.currPage+1}'>[下一页]</a>
</c:if>
<a href='/day0610/DividePageServelt?currPage=${pageBean.totalPageNum}'>【尾页】</a>
${pageBean.currPage}/${pageBean.totalPageNum}页 共${pageBean.totalRecordNum}条记录
</p>
二、商品的添加改查功能:
1.添加商品:
1).新建一个处理添加商品的Servlet:AddProductServlet,新建一个商品添加页面addProduct.jsp。里面加一个商品添加商品种类的表单.2).表单提交到AddProductServlet后,使用request.getParamterMap()得到一个含有所有参数的map集合
3).这里使用BeanUtils直接封装表单Product对象:BeanUtils.populate(product,map);
4).给封装后的Product对象设置一个32位随机字符串的pid属性,使用Java自带UUIDUtils.因为初始生成含有'-'号,使用replace()方法将"-"替代为"";
5).将对象传入Service->dao:使用update进行更新操作。由于对象有10个属性。可以建立一个参数数组Object[] params存储对象的成员值
6).关于重复提交的本质原因是没有对当前页面进行刷新。这里使用令牌(token)的形式对没有刷新页面的提交进行处理。原理和验证码一次性使用一样
在客户端jsp代码中获得一个UUID形式的token。分别存放在客户端的request请求域对象中,和服务端的session中。当有刷新提交访问到服务端,从服务端获取到这个
token。然后移除该session。只要有访问服务端,request域对象的token和session的token是一样的。当第二次再重复提交。第一次的Session中的token被
移除了。拿到的是null的session。
2.模糊查询查找商品:
查寻含有关键字的商品名称,在sql操作中,使用like "%a%"模糊查询来查1)post方式提交pname到处理模糊查询的FindLikeServlet中。先进行中文编码的处理
2)新建一个ProductBean对象。
3)调用ProductService中的List<Product> list=findLike(pname)功能,Dao也创建该方法
4)在Dao的findLike(pname)中,sql语句是"select * from product order by pdate where pname like ?",
后面的参数是"%"+pname+"%"。返回的结果是BeanList;
5)把DAO返回的List<Product> list传递到Servlet中,赋值给productBean.list;
6)productBean存放到session.覆盖原来的seesion
7)
---------mark一下 明天再补全-----------------
3.删除商品
删除商品分为
1)选择多项商品删除
2)单击单项商品删除链接
删除商品中要使用事务机制,这里采用的是DBUtils中的事务封装的方法
4.修改商品:
修改商品。因为request请求发送的是字符串链接。不能上传一个bean对象。所以我们只能把商品id上传到后台,让后台查找到
数据库的商品。然后利用后台的
----------------完善------------------
1.添加/删除/修改/删除所选等操作,添加一个msg信号。在js接收msg。这样子当操作成功的时候,能够弹出一个alert警告框提示操作成功
因为是一次性信号,所以使用reuqest域对象存储信号:
添加成功:"msg","msgAddSuccess"
修改成功:"msg","msgUpdateSuccess"
删除成功:"msg","msgDeleteSuccess"
查询失败:"msg","msgLikeFindError"
【案例:商品的增删改查与分页】代码
一、JSP页面:
1.显示所有商品:
product_list.jsp
这段代码在CSDN提供的编辑器中,生成了<span style="white-space:pre;"> </span>这个东东,请忽略掉。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link rel="stylesheet" type="text/css"
href="/day0610/demo/css/bootstrap.min.css" />
<script src="/day0610/demo/js/jquery-1.8.3.js"></script>
<script src="/day0610/demo/js/bootstrap.min.js"></script>
<script>
$(function() {
// 偶数行表格背景变色
$("table tbody tr:odd").css("background-color", "#AFD9EE");
});
</script>
<style>
* {
margin: 0;
padding: 0;
}
table {
width: 100%;
border-collapse: separate;
border-spacing: 0px;
border-color: grey;
border: 1px solid #aaa;
}
th {
vertical-align: baseline;
padding: 5px 15px 5px 6px;
background-color: #3F3F3F;
border: 1px solid #3F3F3F;
text-align: center;
color: #fff;
}
td {
border: 1px solid #3F3F3F;
padding: 5px 15px 5px 6px;
text-align: center;
}
</style>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function addPage() {
//页面跳转的方法:window.location.href = ${pageContext.request.contextPath}/jsp/demo/product_list.jsp;
window.location.href = "${pageContext.request.contextPath}/demo/jsp/addProduct.jsp";
}
</script>
</head>
<body>
<center>
<h2>商品详情列表</h2>
<tr>
<td colspan=7>商品名称:<input type="text" name="pname"><input
type="submit" value="查询"> <input
type="button" value="添加" οnclick="addPage()" />
</td>
</tr>
<br />
<br />
</center>
<div class="container">
<div class="rows">
<div class="col-lg-12"></div>
</div>
</div>
<div class="container">
<div class="rows">
<div class="col-lg-12">
<table>
<thead>
<tr>
<th>序号</th>
<th>商品名字</th>
<th>市场价格</th>
<th>商品价格</th>
<th>是否热门</th>
<th>是否下架</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="i" items="${productList}" varStatus="status">
<tr>
<td>${status.count}</td>
<td>${i.pname}</td>
<td>${i.market_price}</td>
<td>${i.shop_price}</td>
<td><c:if test="${ i.is_hot == 1 }">
是
</c:if> <c:if test="${ i.is_hot != 1 }">
否
</c:if></td>
<td><c:if test="${ i.is_hot == 1 }">
未下架
</c:if> <c:if test="${ i.is_hot != 1 }">
已下架
</c:if></td>
<td><a href="#">修改</a>|<a href="#">删除</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
2.分页方式显示商品:
product_divide.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link rel="stylesheet" type="text/css"
href="/day0610/demo/css/bootstrap.min.css" />
<script src="/day0610/demo/js/jquery-1.8.3.js"></script>
<script
src="${pageContext.request.contextPath}/demo/js/bootstrap.min.js"></script>
<script>
$(function() {
// 偶数行表格背景变色
$("table tbody tr:odd").css("background-color", "#AFD9EE");
});
$(function() {
$("#select_all").click(function() {
$("input[name='ids']").prop("checked", this.checked);
});
});
</script>
<script type="text/javascript">
window.onload = function() {
var msg = "${msg}";
if (msg == "") {
} else {
alert(msg);
<%request.getSession().removeAttribute("msg");%>
}
};
</script>
<style>
* {
margin: 0;
padding: 0;
}
table {
width: 100%;
border-collapse: separate;
border-spacing: 0px;
border-color: grey;
border: 1px solid #aaa;
}
th {
vertical-align: baseline;
padding: 5px 15px 5px 6px;
background-color: #3F3F3F;
border: 1px solid #3F3F3F;
text-align: center;
color: #fff;
}
td {
border: 1px solid #3F3F3F;
padding: 5px 15px 5px 6px;
text-align: center;
}
</style>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function addPage() {
//页面跳转的方法:window.location.href = ${pageContext.request.contextPath}/jsp/demo/product_list.jsp;
window.location.href = "${pageContext.request.contextPath}/demo/jsp/addProduct.jsp";
}
$(function() {
$("#select_all").click(function() {
$(":input[name='ids']").prop("checked", this.checked);
});
});
</script>
</head>
<body>
<center>
<h2>商品详情列表</h2>
<form action="/day0610/FindProductServlet" method="post">
<tr>
<td colspan=7>商品名称:<input type="text" name="pname"><input
type="submit" value="查询"> <input
type="button" value="添加" οnclick="addPage()" />
</td>
</tr>
</form>
<br /> <br />
</center>
<div class="container">
<div class="rows">
<div class="col-lg-12"></div>
</div>
</div>
<div class="container">
<div class="rows">
<div class="col-lg-12">
<table colspan=8>
<thead>
<tr>
<th>序号</th>
<form action="${pageContext.request.contextPath}/DelRecServlet"
method="post">
<th><input type="submit" value="删除选中商品"
style="background-color: red" /><br /> <input id="select_all"
type="checkbox" /></th>
<th>商品名字</th>
<th>市场价格</th>
<th>商品价格</th>
<th>是否热门</th>
<th>是否下架</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="i" items="${pageBean.list}" varStatus="status">
<tr>
<td>${status.count}</td>
<td><input type="checkbox" name="ids" value="${i.pid}"></td>
<td>${i.pname}</td>
<td>${i.market_price}</td>
<td>${i.shop_price}</td>
<td><c:if test="${ i.is_hot == 1 }">
是
</c:if> <c:if test="${ i.is_hot != 1 }">
否
</c:if></td>
<td><c:if test="${ i.is_hot == 1 }">
未下架
</c:if> <c:if test="${ i.is_hot != 1 }">
已下架
</c:if></td>
<td><a
href="${pageContext.request.contextPath}/FindProductByIdServlet?pid=${i.pid}">修改</a>|
<a
href="${pageContext.request.contextPath}/DelOneServlet?pid=${i.pid}">删除</a></td>
</tr>
</c:forEach>
</form>
</tbody>
</table>
<br /> <br />
<center>
<p>
分页条: <a href='/day0610/DividePageServelt?currPage=1'>【首页】</a>
<c:if test="${pageBean.currPage!=1}">
<a
href='/day0610/DividePageServelt?currPage=${pageBean.currPage-1}'>[上一页]</a>
</c:if>
<c:forEach begin="1" end="${pageBean.totalPageNum}" var="status">
<!--
<c:if test="${status}==${pageBean.currPage}">
[${status}]
</c:if>
<c:if test="${status}!=${pageBean.currPage}">
<a href='/day0610/DividePageServelt?currPage=${status}'>[${status}]</a>
</c:if>
-->
<a href='/day0610/DividePageServelt?currPage=${status}'>[${status}]</a>
</c:forEach>
<c:if test="${pageBean.currPage!=pageBean.totalPageNum}">
<a
href='/day0610/DividePageServelt?currPage=${pageBean.currPage+1}'>[下一页]</a>
</c:if>
<a
href='/day0610/DividePageServelt?currPage=${pageBean.totalPageNum}'>【尾页】</a>
${pageBean.currPage}/${pageBean.totalPageNum}页 共${pageBean.totalRecordNum}条记录
</p>
</center>
</div>
</div>
</div>
</body>
</html>
3.添加商品:
addProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>添加商品</h1>
<form action="/day0610/AddProductServlet" method="post">
<table border="1" width="500">
<tr>
<td>商品名称</td>
<td><input type="text" name="pname"></td>
</tr>
<tr>
<td>市场价格</td>
<td><input type="text" name="market_price"></td>
</tr>
<tr>
<td>商城价格</td>
<td><input type="text" name="shop_price"></td>
</tr>
<tr>
<td>是否热门</td>
<td><input type="radio" name="is_hot" value="1" checked>是<input
type="radio" name="is_hot" value="0">否</td>
</tr>
<tr>
<td>是否下架</td>
<td><select name="plfag">
<option value="1" selected>是</option>
<option value="0">否</option>
</select></td>
</tr>
<tr>
<td>商品描述</td>
<td><textarea rows="4" cols="4" name="pdesc"></textarea></td>
</tr>
<tr>
<td>商品分类</td>
<td><select>
<option selected value="1">手机数码</option>
<option value="2">电脑办公</option>
<option value="3">汽车用品</option>
<option value="4">鞋靴商包</option>
</select></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="addBtn"></td>
</tr>
</table>
</form>
</body>
</html>
4.修改商品
updateProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>修改商品</h1>
<form action="/day0610/UpdateProductServlet" method="post">
<table border="1" width="500">
<tr>
<td>商品名称</td>
<td><input type="text" name="pname" value ="${product.pname}"></td>
</tr>
<tr>
<td>市场价格</td>
<td><input type="text" name="market_price" value ="${product.market_price}"></td>
</tr>
<tr>
<td>商城价格</td>
<td><input type="text" name="shop_price" value ="${product.shop_price}"></td>
</tr>
<tr>
<td>是否热门</td>
<td><input type="radio" name="is_hot" value="1" checked="${product.is_hot==1}?'checked':''">是<input
type="radio" name="is_hot" value="0" checked="${product.is_hot==1}?'checked':''">否</td>
</tr>
<tr>
<td>是否下架</td>
<td><select name="plfag">
<option value="1" selected>是</option>
<option value="0">否</option>
</select></td>
</tr>
<tr>
<td>商品描述</td>
<td><textarea rows="4" cols="4" name="pdesc" value="${product.pdesc}"></textarea></td>
</tr>
<tr>
<td>商品分类</td>
<td><select>
<option selected value="1">手机数码</option>
<option value="2">电脑办公</option>
<option value="3">汽车用品</option>
<option value="4">鞋靴商包</option>
</select></td>
</tr>
<tr>
<input type="hidden" name = "pid" value="${product.pid}"/>
</tr>
<tr>
<td colspan="1"><input type="submit" name="updateBtn" value="确认修改"></td>
</tr>
</table>
</form>
</body>
</html>
5.首页:index.jsp
有显示所有商品链接,分页显示所有商品链接
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品信息管理平台</title>
</head>
<body>
<h1>欢迎来到商品信息管理平台</h1>
<h3>
<a href='${pageContext.request.contextPath}/ProductFindAllServlet'>查询所有商品</a>
<a href='${pageContext.request.contextPath}/DividePageServelt?currPage=1'>分页查询商品</a>
</h3>
</body>
</html>
二、后台Servlet代码:
【Servlet层】
1.ProductFindAllServlet.java:
用来显示所有商品。(没有分页效果)
public class ProductFindAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 查询所有商品.
try {
List<Product> productList = ProductService.findAll();
// //查询结果添加到Session中
// request.getSession().setAttribute("productList", productList);
// //跳转到商品展示页面
// response.sendRedirect("/day0610/demo/product_list.jsp");
request.setAttribute("productList", productList);
//转发自带项目名路径
request.getRequestDispatcher("demo/jsp/product_list.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2.DividePageServelt.java
分页效果显示所有数据库的商品:
package com.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.web.domain.PageBean;
import com.web.domain.Product;
import com.web.service.ProductService;
/**
*/
public class DividePageServelt extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int currPage = Integer.parseInt(request.getParameter("currPage"));
System.out.println(currPage);
PageBean pageBean = new PageBean();
int begin = (currPage - 1) * 10;
int size = PageBean.getPageSize();
int totalRecordNum = 0;
List<Product> list = null;
try {
totalRecordNum = ProductService.getRecordNum();
list = ProductService.findAllByLimit(begin, size);
} catch (Exception e) {
}
// 计算总页数:
Double totalPageNum = Math.ceil((double) totalRecordNum / size);
// 设置属性:
pageBean.setCurrPage(currPage);
pageBean.setTotalPageNum(totalPageNum.intValue());
pageBean.setTotalRecordNum(totalRecordNum);
pageBean.setList(list);
// 转发页面
//先更新PageBean属性
request.setAttribute("pageBean", pageBean);
request.getRequestDispatcher("demo/jsp/product_divide.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
3.AddProductServlet.java
添加商品
package com.web.servlet;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.web.domain.Product;
import com.web.service.ProductService;
import com.web.utils.UUIDUtils;
/**
*/
public class AddProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddProductServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收参数:
// 封装数据:
// 调用业务层:
// 页面跳转:
int rs = 0;
try {
request.setCharacterEncoding("UTF-8");
Map<String, String[]> map = request.getParameterMap();
// BeanUtil封装数据
Product product = new Product();
BeanUtils.populate(product, map);
// 生成一个随机id:随机生成。使用UUID工具类
product.setPid(UUIDUtils.getUUID());
product.setpDate(new Date());
System.out.println(product);
rs = ProductService.save(product);
} catch (Exception e) {
System.out.println("SERV:" + e.toString());
}
if (rs > 0) {
//request.setAttribute("msg", "添加商品成功");
//request.getRequestDispatcher("/DividePageServelt?currPage=1").forward(request, response);
request.getSession().setAttribute("msg","添加商品成功");
//添加成功
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
} else {
request.getSession().setAttribute("msg", "添加商品失败");
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
4.DelRecServlet.java
删除选中的多个商品(在Service层带有事务处理机制)
package com.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.web.service.ProductService;
/**
* Servlet implementation class DelRecServlet
*/
public class DelRecServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] ids = request.getParameterValues("ids");
System.out.println("被访问了");
System.out.println("ids:"+ids.length);
int rs = 0;
try {
rs = ProductService.deleteMany(ids);
} catch (Exception e) {
}
if(rs>0)
{
request.getSession().setAttribute("msg", "删除商品成功");
//删除成功以后,转移到分页的Servlet。
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
System.out.println("删除成功");
}
else {
request.getSession().setAttribute("msg", "删除商品失败");
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
System.out.println("删除失败");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("2222");
doGet(request, response);
}
}
5.DelOneServlet.java
删除一个商品
package com.web.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.web.service.ProductService;
import sun.net.www.content.audio.wav;
/**
* Servlet implementation class DelOneServlet
*/
public class DelOneServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pid = request.getParameter("pid");
System.out.println(pid);
int rs = 0;
try {
rs=ProductService.delOne(pid);
} catch (SQLException e) {
}
if(rs>0)
{
request.getSession().setAttribute("msg","删除商品成功");
System.out.println("删除一个成功");
//删除成功
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
}
else
{
request.getSession().setAttribute("msg", "删除商品失败");
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
System.out.println("删除一个失败");
//删除失败
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
6.FindProductServlet.java
关键字查找商品
package com.web.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.taglibs.standard.lang.jstl.NullLiteral;
import com.web.domain.PageBean;
import com.web.domain.Product;
import com.web.service.ProductService;
import sun.applet.resources.MsgAppletViewer;
import sun.net.www.content.audio.wav;
public class FindProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String pname = request.getParameter("pname");
System.out.println(pname);
PageBean pageBean = new PageBean();
List<Product> list = null;
try {
list = ProductService.findLike(pname);
} catch (SQLException e) {
e.printStackTrace();
}
// 判断结果
if (list != null) {
pageBean.setList(list);
request.setAttribute("pageBean", pageBean);
request.getRequestDispatcher("demo/jsp/product_divide.jsp").forward(request, response);
} else {
request.setAttribute("msg", "没有要查询的商品,请重新输入");
request.getRequestDispatcher("demo/jsp/product_divide.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
7.FindProductByIdServlet
修改商品:因为要先获得该商品项的所有信息,在修改页面显示。所以我们先上传该商品的id到后台查找到数据库中的商品信息,再跳转到修改商品信息的页面
package com.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.web.domain.Product;
import com.web.service.ProductService;
/**
* Servlet implementation class FindProductByIdServlet
*/
public class FindProductByIdServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pid = request.getParameter("pid");
System.out.println(pid.length());
//Product product = new Product();
try {
Product product = ProductService.getProduct(pid);
System.out.println(product);
request.setAttribute("product", product);
request.getRequestDispatcher("/demo/jsp/updateProduct.jsp").forward(request, response);
} catch (Exception e) {
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
8.UpdateProductServlet.java
把修改页面中修改好的所有信息上传到后台进行更新操作
package com.web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.web.domain.Product;
import com.web.service.ProductService;
/**
*/
public class UpdateProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Map<String, String[]> map = request.getParameterMap();
Product product = new Product();
int rs = 0;
try {
BeanUtils.populate(product, map);
rs=ProductService.updateOne(product);
} catch (Exception e) {
e.printStackTrace();
}
if(rs>0)
{
request.getSession().setAttribute("msg", "修改商品成功");
System.out.println("修改成功");
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
}
else
{
request.getSession().setAttribute("msg", "修改商品失败");
response.sendRedirect("/day0610/DividePageServelt?currPage=1");
System.out.println("修改失败");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
【Service层】
1.ProductService.java
这里包含了所有Servlet要处理的业务项。
package com.web.service;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import com.sun.media.jfxmedia.control.VideoDataBuffer;
import com.web.dao.ProductDao;
import com.web.domain.Product;
import com.web.utils.C3P0Utils;
public class ProductService {
public static List<Product> findAll() throws SQLException {
List<Product> list = ProductDao.queryAll();
return list;
}
public static int save(Product product) throws SQLException {
return ProductDao.save(product);
}
public static int getRecordNum() throws SQLException {
int count = ProductDao.getCount();
return count;
}
public static List<Product> findAllByLimit(int begin, int size) throws SQLException {
List<Product> list = ProductDao.findAllByLimit(begin, size);
return list;
}
public static List<Product> findLike(String pname) throws SQLException {
List<Product> list = ProductDao.findLike(pname);
return list;
}
public static int deleteMany(String[] ids) throws SQLException {
/*
* 使用事务:
*/
int rs = 0;
Connection conn = null;
try {
conn = C3P0Utils.getConnection();
conn.setAutoCommit(false);
rs = ProductDao.deleteMany(conn,ids);
// int i = 1 / 0;
DbUtils.commitAndCloseQuietly(conn);
} catch (Exception e) {
System.out.println("DAO发生异常:");
DbUtils.rollbackAndCloseQuietly(conn);
return -1;
}
return rs;
}
public static Product getProduct(String pid) throws SQLException {
Product product = ProductDao.QueryOne(pid);
return product;
}
public static int updateOne(Product product) throws SQLException {
return ProductDao.updateOne(product);
}
public static int delOne(String pid) throws SQLException {
int rs = ProductDao.delOne(pid);
return rs;
}
}
【DAO层】
ProductDao.java
数据库的增删该查操作
package com.web.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.web.domain.Product;
import com.web.utils.C3P0Utils;
public class ProductDao {
private static final QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
/*
* 查询所有商品
*/
public static List<Product> queryAll() throws SQLException {
String sql = "select * from product order by pdate desc";
List<Product> list = (ArrayList<Product>) queryRunner.query(sql, new BeanListHandler<Product>(Product.class));
return list;
}
/*
* 添加商品到表中:保存商品
*/
public static int save(Product product) throws SQLException {
String sql = "insert into product values(?,?,?,?,?,?,?,?,?,?)";
Object[] params = { product.getPid(), product.getPname(), product.getMarket_price(), product.getShop_price(),
product.getPimage(), product.getpDate(), product.getIs_hot(), product.getPdesc(), product.getPflag(),
product.getCid() };
System.out.println("有访问到DAO吗");
int rs = queryRunner.update(sql, params);
System.out.println("DAO_rs:"+rs);
return rs;
}
/*
* 获取表的总记录数
*/
public static int getCount() throws SQLException {
String sql = "select count(*) from product order by pdate desc";
Long count = (Long) queryRunner.query(sql, new ScalarHandler());
return count.intValue();
}
/*
* 分页查询所有商品
*/
public static List<Product> findAllByLimit(int begin, int size) throws SQLException {
String sql = "select * from product order by pdate desc limit ?,?";
List<Product> list = queryRunner.query(sql, new BeanListHandler<Product>(Product.class), begin, size);
return list;
}
public static List<Product> findLike(String pname) throws SQLException {
List<Product> list = queryRunner.query("select * from product where pname like ?",
new BeanListHandler<Product>(Product.class), "%" + pname + "%");
return list;
}
/*
* 删除多个商品
*/
public static int deleteMany(Connection conn, String[] ids) throws SQLException {
int rs = 0;
StringBuffer sql = new StringBuffer("delete from product where pid in (");
int idSize = ids.length;
for (int i = 0; i < idSize; i++) {
sql.append("?,");
}
String newSql = sql.substring(0, sql.length() - 1) + ")";
System.out.println(newSql);
PreparedStatement pst = conn.prepareStatement(newSql);
for (int i = 0; i < idSize; i++) {
pst.setString(i + 1, ids[i]);
System.out.print(ids[i] + " ");
}
rs = pst.executeUpdate();
System.out.println("是否删除成功:" + rs);
return rs;
}
/*
* 查询一个
*/
public static Product QueryOne(String pid) throws SQLException {
String sql = "select * from product where pid = ?";
Product product = queryRunner.query(sql, new BeanHandler<Product>(Product.class), pid);
return product;
}
/*
* 修改一个
*/
public static int updateOne(Product product) throws SQLException {
String sql = "update product set pname =?,market_price=?,shop_price=?,is_hot=?,pdesc=?,pflag=? where pid=?";
int rs = 0;
rs = queryRunner.update(sql, product.getPname(), product.getMarket_price(), product.getShop_price(),
product.getIs_hot(), product.getPdesc(), product.getPflag(), product.getPid());
return rs;
}
/*
* 删除一个
*/
public static int delOne(String pid) throws SQLException {
String sql = "delete from product where pid=?";
int rs = queryRunner.update(sql, pid);
return rs;
}
}
【Bean层】
实体类PageBean.java处理的是进行分页显示时候所需要的页面信息
实体类Product.java是商品的所有字段属性
1.PageBean.java
package com.web.domain;
import java.util.List;
public class PageBean {
private int currPage;
private int totalPageNum;
private int totalRecordNum;
private static final int PAGE_SIZE = 10;
private List<Product> list;
public PageBean() {
super();
// TODO Auto-generated constructor stub
}
public PageBean(int currPage, int totalPageNum, int totalRecordNum, List<Product> list) {
super();
this.currPage = currPage;
this.totalPageNum = totalPageNum;
this.totalRecordNum = totalRecordNum;
this.list = list;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public int getTotalPageNum() {
return totalPageNum;
}
public void setTotalPageNum(int totalPageNum) {
this.totalPageNum = totalPageNum;
}
public int getTotalRecordNum() {
return totalRecordNum;
}
public void setTotalRecordNum(int totalRecordNum) {
this.totalRecordNum = totalRecordNum;
}
public List<Product> getList() {
return list;
}
public void setList(List<Product> list) {
this.list = list;
}
public static int getPageSize() {
return PAGE_SIZE;
}
@Override
public String toString() {
return "PageBean [currPage=" + currPage + ", totalPageNum=" + totalPageNum + ", totalRecordNum="
+ totalRecordNum + ", list=" + list + "]";
}
}
2.Product.java
package com.web.domain;
import java.util.Date;
public class Product {
private String pid;
private String pname;
private double market_price;
private double shop_price;
private String pimage;
private Date pDate;
private int is_hot;
private String pdesc;
private int pflag;
private String cid;
public Product() {
// TODO Auto-generated constructor stub
}
public Product(String pid, String pname, double market_price, double shop_price, String pimage, Date pDate,
int is_hot, String pdesc, int pflag, String cid) {
super();
this.pid = pid;
this.pname = pname;
this.market_price = market_price;
this.shop_price = shop_price;
this.pimage = pimage;
this.pDate = pDate;
this.is_hot = is_hot;
this.pdesc = pdesc;
this.pflag = pflag;
this.cid = cid;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getMarket_price() {
return market_price;
}
public void setMarket_price(double market_price) {
this.market_price = market_price;
}
public double getShop_price() {
return shop_price;
}
public void setShop_price(double shop_price) {
this.shop_price = shop_price;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public Date getpDate() {
return pDate;
}
public void setpDate(Date pDate) {
this.pDate = pDate;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
public int getPflag() {
return pflag;
}
public void setPflag(int pflag) {
this.pflag = pflag;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Product [pid=" + pid + ", pname=" + pname + ", market_price=" + market_price + ", shop_price="
+ shop_price + ", pimage=" + pimage + ", pDate=" + pDate + ", is_hot=" + is_hot + ", pdesc=" + pdesc
+ ", pflag=" + pflag + ", cid=" + cid + "]";
}
}