day02 --最新和热门商品 ajax显示类别菜单 分页显示列表 商品详细信息 浏览历史记录 分页
一、获取最新商品和热门商品
IndexServlet
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
ProductService service = new ProductService();
//准备热门商品---List<Product>
List<Product> hotProductList = service.findHotProductList();
//准备最新商品---List<Product>
List<Product> newProductList = service.findNewProductList();
request.setAttribute("hotProductList", hotProductList);
request.setAttribute("newProductList", newProductList);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ProductService
public class ProductService {
//获得热门商品
public List<Product> findHotProductList() {
ProductDao dao = new ProductDao();
List<Product> hotProductList = null;
try {
hotProductList = dao.findHotProductList();
} catch (SQLException e) {
e.printStackTrace();
}
return hotProductList;
}
//获得最新商品
public List<Product> findNewProductList() {
ProductDao dao = new ProductDao();
List<Product> newroductList = null;
try {
newroductList = dao.findNewProductList();
} catch (SQLException e) {
e.printStackTrace();
}
return newroductList;
}
}
ProductDao
public class ProductDao {
//获得热门商品
public List<Product> findHotProductList() throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product where is_hot = ? limit ?,?";
return runner.query(sql, new BeanListHandler<Product>(Product.class),1,0,9);
}
//获得最新商品
public List<Product> findNewProductList() throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product order by pdate desc limit ?,?";
return runner.query(sql, new BeanListHandler<Product>(Product.class), 0,9);
}
}
index.jsp
热门商品:
<c:forEach items="${hotProductList }" var="hotPro">
<div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
<a href="product_info.htm">
<img src="${pageContext.request.contextPath }/${hotPro.pimage }" width="130" height="130" style="display: inline-block;">
</a>
<p><a href="product_info.html" style='color:#666'>${hotPro.pname }</a></p>
<p><font color="#E4393C" style="font-size:16px">¥${hotPro.shop_price }</font></p>
</div>
</c:forEach>
最新商品:
<c:forEach items="${newProductList }" var="newPro">
<div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
<a href="product_info.htm">
<img src="${pageContext.request.contextPath }/${newPro.pimage }" width="130" height="130" style="display: inline-block;">
</a>
<p><a href="product_info.html" style='color:#666'>${newPro.pname }</a></p>
<p><font color="#E4393C" style="font-size:16px">¥${newPro.shop_price }</font></p>
</div>
</c:forEach>
二、使用ajax显示类别菜单
header.jsp
<script type="text/javascript">
//header.jsp加载完毕后 去服务器端获得所有的category数据
$(function(){
var content = "";
$.post(
"${pageContext.request.contextPath}/categoryList",
function(data){
//[{"cid":"xxx","cname":"xxxx"},{},{}]
//动态创建<li><a href="#">${category.cname }</a></li>
for(var i=0;i<data.length;i++){
content+="<li><a href='${pageContext.request.contextPath}/productListByCid?cid="+data[i].cid+"'>"+data[i].cname+"</a></li>";
}
//将拼接好的li放置到ul中
$("#categoryUL").html(content);
},
"json"
);
});
</script>
CategoryList
public class CategoryListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
ProductService service = new ProductService();
//先从缓存中查询categoryList,如果有,直接使用,没有,再从数据库中查询,存到缓存中
//1.获得jedis对象,连接redis数据库
Jedis jedis = JedisPoolUtils.getJedis();
String categoryListJson = jedis.get("categoryListJson");
//2.判断categoryListJson是否为空
if(categoryListJson == null){
System.out.println("缓存没有数据,从数据库取");
//准备分类数据
List<Category> categoryList = service.findAllCategory();
Gson gson = new Gson();
categoryListJson = gson.toJson(categoryList);
jedis.set("categoryListJson", categoryListJson);
}
response.getWriter().write(categoryListJson);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ProductService
public class ProductService {
//获得商品类别
public List<Category> findAllCategory() {
ProductDao dao = new ProductDao();
List<Category> categoryList = null;
try {
categoryList = dao.findAllCategory();
} catch (SQLException e) {
e.printStackTrace();
}
return categoryList;
}
}
ProductDao
public class ProductDao {
//获得商品类别
public List<Category> findAllCategory() throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from category";
return runner.query(sql, new BeanListHandler<Category>(Category.class));
}
}
三、分页显示某种类别的商品列表
ProductListByCidServlet
public class ProductListByCidServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
//获得cid
String cid = request.getParameter("cid");
String currentPageStr = request.getParameter("currentPage");
if(currentPageStr == null){
currentPageStr = "1";
}
int currentPage = Integer.parseInt(currentPageStr);
int currentCount = 12;
ProductService service = new ProductService();
PageBean pageBean = service.findProductListByCid(cid,currentPage,currentCount);
request.setAttribute("pageBean", pageBean);
request.setAttribute("cid", cid);
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ProductService
public class ProductService {
//分页
public PageBean findProductListByCid(String cid,int currentPage,int currentCount) {
ProductDao dao = new ProductDao();
//封装一个PageBean,返回web层
PageBean<Product> pageBean = new PageBean<Product>();
/*int currentPage = 1;
int currentCount = 12;*/
//1.封装当前页
pageBean.setCurrentPage(currentPage);
//2.封装每页显示的条数
pageBean.setCurrentCount(currentCount);
//3.封装总条数
int totalCount = 0;
try {
totalCount = dao.getCount(cid);
} catch (SQLException e) {
e.printStackTrace();
}
pageBean.setTotalCount(totalCount);
//4.封装总页数
int totalPage = (int) Math.ceil(1.0*totalCount/currentCount);
pageBean.setTotalPage(totalPage);
//5.当前页显示的数据
//select * from product where cid=? limit ?,?
//当前页与起始索引index的关系
int index = (currentPage-1)*currentCount;
List<Product> list = null;
try {
list = dao.findProductByPage(cid,index,currentCount);
} catch (SQLException e) {
e.printStackTrace();
}
pageBean.setList(list);
return pageBean;
}
}
ProdcuctDao
public class ProductDao {
//获得总条数
public int getCount(String cid) throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select count(*) from product where cid = ?";
Long query = (long) runner.query(sql, new ScalarHandler(),cid);
return query.intValue();
}
//获得每一页的数据
public List<Product> findProductByPage(String cid, int index, int currentCount) throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product where cid = ? limit ?,?";
List<Product> list = runner.query(sql, new BeanListHandler<Product>(Product.class),cid,index,currentCount);
return list;
}
}
product_list.jsp
<div class="row" style="width: 1210px; margin: 0 auto;">
<div class="col-md-12">
<ol class="breadcrumb">
<li><a href="#">首页</a></li>
</ol>
</div>
<c:forEach items="${pageBean.list }" var="pro" >
<div class="col-md-2" style="height:250px">
<a href="${pageContext.request.contextPath}/productInfo?pid=${pro.pid}&cid=${cid}¤tPage=${pageBean.currentPage}">
<img src="${pageContext.request.contextPath}/${pro.pimage}" width="170" height="170" style="display: inline-block;">
</a>
<p>
<a href="${pageContext.request.contextPath}/productInfo?pid=${pro.pid}&cid=${cid}¤tPage=${pageBean.currentPage}" style='color: green'>${pro.pname }</a>
</p>
<p>
<font color="#FF0000">商城价:¥${pro.shop_price }</font>
</p>
</div>
</c:forEach>
</div>
<!--分页 -->
<div style="width: 380px; margin: 0 auto; margin-top: 50px;">
<ul class="pagination" style="text-align: center; margin-top: 10px;">
<!-- 上一页 -->
<c:if test="${pageBean.currentPage==1 }">
<li class="disabled">
<a href="javascript:void(0);" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:if test="${pageBean.currentPage!=1 }">
<li class="disabled">
<a href="${pageContext.request.contextPath }/productListByCid?cid=${cid}¤tPage=${pageBean.currentPage-1}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<!-- 显示每一页 -->
<c:forEach begin="1" end="${pageBean.totalPage }" var="page"> <!-- 代表当前条目的变量名称 -->
<!-- 判断是否是当前页 -->
<c:if test="${page==pageBean.currentPage }">
<li class="active"><a href="javascrip:void(0);">${page }</a></li>
</c:if>
<c:if test="${page!=pageBean.currentPage }">
<a href="${pageContext.request.contextPath }/productListByCid?cid=${cid}¤tPage=${page}">${page }</a></li>
</c:if>
</c:forEach>
<!-- 下一页 -->
<c:if test="${pageBean.currentPage==pageBean.totalPage }">
<li class="disabled">
<a href="javascript:void(0);" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<c:if test="${pageBean.currentPage!=pageBean.totalPage }">
<li>
<a href="${pageContext.request.contextPath }/productListByCid?cid=${cid}¤tPage=${pageBean.currentPage+1}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
</ul>
</div>
<!-- 分页结束 -->
四、显示商品详细信息、浏览历史记录
ProductInfoServlet
public class ProductInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
//获得当前页
String currentPage = request.getParameter("currentPage");
//获得商品类别
String cid = request.getParameter("cid");
//获得要查询的商品的pid
String pid = request.getParameter("pid");
ProductService service = new ProductService();
Product product = service.findProductByPid(pid);
request.setAttribute("product",product);
request.setAttribute("currentPage", currentPage);
request.setAttribute("cid", cid);
//获得客户管携带的cookie---获得名字是pids的cookie
String pids = pid;
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for(Cookie cookie:cookies){
if("pids".equals(cookie.getName())){
pids = cookie.getValue();
//1-3-2 本次访问的商品id是8, 8-1-3-2
//1-3-2本次访问的商品id是3, 3-1-2
//将pids拆成一个数组
String[] split = pids.split("-"); //{3,1,2}
List<String> asList = Arrays.asList(split);// [3,1,2]
LinkedList<String> list = new LinkedList<String>(asList);// [3,1,2]
//判断集合中是否存在当前的pid
if(list.contains(pid)){
//包含当前查看商品的pid
list.remove(pid);
list.addFirst(pid);
}else{
//不包含当前查看商品的pid,直接把该pid放在头上
list.addFirst(pid);
}
//将[3,1,2]转成3-1-2字符串
StringBuffer sb = new StringBuffer();
for(int i=0;i<list.size();i++){
sb.append(list.get(i));
sb.append("-"); //3-1-2-
}
//去掉3-1-2-后的-
pids = sb.substring(0,sb.length()-1);
}
}
}
Cookie cookie_pids = new Cookie("pids",pids);
response.addCookie(cookie_pids);
request.getRequestDispatcher("/product_info.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
product_info.jsp
<div style="margin: 0 auto; width: 950px;">
<div class="col-md-6">
<img style="opacity: 1; width: 400px; height: 350px;" title=""
class="medium"
src="${pageContext.request.contextPath }/${product.pimage}">
</div>
<div class="col-md-6">
<div>
<strong>${pageContext.request.contextPath }/${product.pname }</strong>
</div>
<div
style="border-bottom: 1px dotted #dddddd; width: 350px; margin: 10px 0 10px 0;">
<div>编号:${product.pid }</div>
</div>
<div style="margin: 10px 0 10px 0;">
亿家价: <strong style="color: #ef0101;">¥:${product.shop_price }元/份</strong> 参 考 价:
<del>¥${product.market_price }元/份</del>
</div>
<div style="margin: 10px 0 10px 0;">
促销: <a target="_blank" title="限时抢购 (2014-07-30 ~ 2015-01-01)"
style="background-color: #f07373;">限时抢购</a>
</div>
<div
style="padding: 10px; border: 1px solid #e7dbb1; width: 330px; margin: 15px 0 10px 0;; background-color: #fffee6;">
<div style="margin: 5px 0 10px 0;">白色</div>
<div
style="border-bottom: 1px solid #faeac7; margin-top: 20px; padding-left: 10px;">
购买数量:
<input id="buyNum" name="quantity" value="1" maxlength="4" size="10" type="text">
</div>
<div style="margin: 20px 0 10px 0;; text-align: center;">
<a href="javascript:void(0);" onclick="addCart();">
<input style="background: url('./images/product.gif') no-repeat scroll 0 -600px rgba(0, 0, 0, 0); height: 36px; width: 127px;" value="加入购物车" type="button">
</a> 收藏商品
</div>
</div>
<div>
<a href="${pageContext.request.contextPath }/productListByCid?cid=${cid}¤tPage=${currentPage}">返回列表页面</a>
</div>
</div>
</div>
ProductListByCidServlet
public class ProductListByCidServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
//定义一个记录历史商品信息的集合
List<Product> historyProductList = new ArrayList<Product>();
//在转发之前要获得客户端携带的名字叫pids的cookie
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for(Cookie cookie:cookies){
if("pids".equals(cookie.getName())){
String pids = cookie.getValue();//3-2-1
String[] split = pids.split("-");
for(String pid:split){
Product pro = service.findProductByPid(pid);
historyProductList.add(pro);
}
}
}
}
//将历史记录的集合放入域
request.setAttribute("historyProductList",historyProductList);
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ProductService
public class ProductService {
//根据id查询商品
public Product findProductByPid(String pid) {
ProductDao dao = new ProductDao();
Product product = null;
try {
product = dao.findProductByPid(pid);
} catch (SQLException e) {
e.printStackTrace();
}
return product;
}
}
ProductDao
public class ProductDao {
//根据id查询商品
public Product findProductByPid(String pid) throws SQLException {
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product where pid = ? ";
Product product = runner.query(sql,new BeanHandler<Product>(Product.class), pid);
return product;
}
}
product_list.jsp
<!--商品浏览记录-->
<div
style="width: 1210px; margin: 0 auto; padding: 0 9px; border: 1px solid #ddd; border-top: 2px solid #999; height: 246px;">
<h4 style="width: 50%; float: left; font: 14px/30px 微软雅黑">浏览记录</h4>
<div style="width: 50%; float: right; text-align: right;">
<a href="">more</a>
</div>
<div style="clear: both;"></div>
<div style="overflow: hidden;">
<ul style="list-style: none;">
<c:forEach items="${historyProductList}" var="historyPro">
<li style="width: 150px; height: 216; float: left; margin: 0 8px 0 0; padding: 0 18px 15px; text-align: center;">
<img src="${pageContext.request.contextPath }/${historyPro.pimage}" xxxwidth="130px" height="130px" />
</li>
</c:forEach>
</ul>
</div>
</div>
PageBean
package com.itheima.domain;
import java.util.List;
public class PageBean<T> {
//当前页码
private int currentPage;
//每页显示条数
private int currentCount;
//总条数
private int totalCount;
//总页数
private int totalPage;
private List<T> list;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getCurrentCount() {
return currentCount;
}
public void setCurrentCount(int currentCount) {
this.currentCount = currentCount;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
}

浙公网安备 33010602011771号