本文主要是介绍【JavaWeb】网上蛋糕项目商城-商品分类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
概念
上一文中,我们实现了首页的数据展示,本文讲解商品分类的商品展示,实现分页显示功能。
点击商品分类中的各种分类,向服务器发送请求,获取数据库中对应该分类的所有商品并以分页的形式返回显示。
商品分类步骤实现
当点击商品分类中的某一项分类时,head.jsp头部页面中触发超链接点击事件,向服务器发送商品分类id
在servlet包中,创建GoodsListServlet类,用于接收用户在浏览器中触发的超链接的点击事件发送的请求
package servlet;import model.Page;
import model.Type;
import service.GoodsService;
import service.TypeService;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;@WebServlet(name = "goods_List",urlPatterns = "/goods_list")
public class GoodsListServlet extends HttpServlet {//商品信息业务逻辑层private GoodsService gService=new GoodsService();//商品分类信息业务逻辑层private TypeService tService=new TypeService();protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int id=0;//获得分类idif(request.getParameter("typeid")!=null){//将分类id从字符串类型转换成int类型id=Integer.parseInt(request.getParameter("typeid"));}int pageNumber=1;//判断是否获得分页页码if(request.getParameter("pageNumber")!=null) {try {//如果获得转换成int类型pageNumber=Integer.parseInt(request.getParameter("pageNumber"));}catch (Exception e){}}Type t=null;if(id!=0){ //根据分类id查询数据库,获得该分类的信息t=tService.selectTypeNameByID(id);}//将分类的信息存储至request对象request.setAttribute("t",t);//List<Goods> list=gService.selectGoodsByTypeID(id,1,8);//request.setAttribute("goodsList",list);if(pageNumber<=0)//当没有设定页码时,默认页码为第一页pageNumber=1;//根据页码以及分类id查询商品表,将该分类商品进行分页获取Page p=gService.selectPageByTypeID(id,pageNumber);//如果查询到该分类的商品不足一页时if(p.getTotalPage()==0){ //则显示为1页p.setTotalPage(1);p.setPageNumber(1);}else {//当用户传递的页码大于数据库查询的总页数时if(pageNumber>=p.getTotalPage()+1){//则默认获取该分类的最后一页的商品信息p=gService.selectPageByTypeID(id,p.getTotalPage());}}//将商品分页信息存储至request对象request.setAttribute("p",p);//将分类id存储至request对象request.setAttribute("id",String.valueOf(id));//请求转发跳转至商品列表页面request.getRequestDispatcher("/goods_list.jsp").forward(request,response);}
}
以上代码中,需要获取用户需要查询的商品分类的id作为查询条件,发送给分类业务逻辑层,因此在TypeService类中定义selectTypeNameByID方法接收分类id
//根据分类id查询分类名字和idpublic Type selectTypeNameByID(int typeid){Type type=null;try {type=tDao.selectTypeNameByID(typeid);} catch (SQLException e) {e.printStackTrace();}return type;}
而业务逻辑层调用数据访问层执行sql语句,因此在TypeDao类中定义selectTypeNameByID方法
//根据分类id查询分类信息public Type selectTypeNameByID(int typeid) throws SQLException {QueryRunner r=new QueryRunner(DataSourceUtils.getDataSource());String sql="select * from type where id=?";return r.query(sql,new BeanHandler<Type>(Type.class),typeid);}
接着需要根据分类id以及页码作为条件查询商品业务逻辑层,因此需要在GoodsService类中定义selectPageByTypeID方法,查询该分类的所有商品,并进行分页
//根据分类id查询分页信息
public Page selectPageByTypeID(int typeID,int pageNumber)
{Page p=new Page();p.setPageNumber(pageNumber);int totalCount=0;try {totalCount=gDao.getCountOfGoodsByTypeID(typeID);} catch (SQLException e) {e.printStackTrace();}//设置每页显示8条数据p.SetPageSizeAndTotalCount(8,totalCount);List list=null;try {list=gDao.selectGoodsByTypeID(typeID,pageNumber,8);} catch (SQLException e) {e.printStackTrace();}p.setList(list);return p;
}
该方法中需要封装Page类保存商品分页信息,因此需要在model包中创建Page实体类
package model;import java.util.List;public class Page {private int pageNumber;private int pageSize;private int totalCount;private int totalPage;private List<Object> list;public void SetPageSizeAndTotalCount(int pageSize,int totalCount){this.pageSize=pageSize;this.totalCount=totalCount;totalPage= (int)Math.ceil((double)totalCount/pageSize);}public int getPageNumber() {return pageNumber;}public void setPageNumber(int pageNumber) {this.pageNumber = pageNumber;}public int getPageSize() {return pageSize;}public void setPageSize(int pageSize) {this.pageSize = pageSize;}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<Object> getList() {return list;}public void setList(List<Object> list) {this.list = list;}
}
接着将分类id作为查询条件发送给GoodsDao查询该分类下的所有商品总数
//根据分类id查询商品总数量
public int getCountOfGoodsByTypeID(int typeID) throws SQLException {String sql="";QueryRunner r=new QueryRunner(DataSourceUtils.getDataSource());if(typeID==0){sql="select count(*) from goods";return r.query(sql,new ScalarHandler<Long>()).intValue();}else{sql="select count(*) from goods where type_id=?";return r.query(sql,new ScalarHandler<Long>(),typeID).intValue();}
}
接着将分类id,页码以及每页显示的商品数量作为条件查询数据库
//根据类型id分页查询该类型下的所有商品信息
public List<Goods> selectGoodsByTypeID(int typeID,int pageNumber,int pageSize) throws SQLException {if(typeID==0){String sql="select * from goods limit ? , ?";QueryRunner r=new QueryRunner(DataSourceUtils.getDataSource());return r.query(sql,new BeanListHandler<Goods>(Goods.class),(pageNumber-1)*pageSize,pageSize);}else{String sql="select * from goods where type_id=? limit ? , ?";QueryRunner r=new QueryRunner(DataSourceUtils.getDataSource());return r.query(sql,new BeanListHandler<Goods>(Goods.class),typeID,(pageNumber-1)*pageSize,pageSize);}
}
这里需要将商品信息封装成实体类,进行存储,因此在model包中创建Goods商品实体类
package model;public class Goods {private int id;private String name;private String cover;private String image1;private String image2;private float price;private String intro;private int stock;private Type type;private boolean isScroll;private boolean isHot;private boolean isNew;public boolean getIsScroll() {return isScroll;}public void setScroll(boolean isScroll) {this.isScroll = isScroll;}public boolean getIsHot() {return isHot;}public void setHot(boolean isHot) {this.isHot = isHot;}public boolean getIsNew() {return isNew;}public void setNew(boolean isNew) {this.isNew = isNew;}public void setTypeid(int typeid) {if(type==null) {type = new Type();}type.setId(typeid);}public void setTypename(String typename) {if(type==null) {type = new Type();}type.setName(typename);}@Overridepublic String toString() {return "Goods [id=" + id + ", name=" + name + ", cover=" + cover + ", image1=" + image1 + ", image2=" + image2+ ", price=" + price + ", intro=" + intro + ", stock=" + stock + ", type=" + type + "]";}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCover() {return cover;}public void setCover(String cover) {this.cover = cover;}public String getImage1() {return image1;}public void setImage1(String image1) {this.image1 = image1;}public String getImage2() {return image2;}public void setImage2(String image2) {this.image2 = image2;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public String getIntro() {return intro;}public void setIntro(String intro) {this.intro = intro;}public int getStock() {return stock;}public void setStock(int stock) {this.stock = stock;}public Type getType() {return type;}public void setType(Type type) {this.type = type;}public Goods() {super();}public Goods(int id, String name, String cover, String image1, String image2, float price, String intro, int stock,Type type) {super();this.id = id;this.name = name;this.cover = cover;this.image1 = image1;this.image2 = image2;this.price = price;this.intro = intro;this.stock = stock;this.type = type;}}
最后将查询的该分类的商品数据发送给goods_list.jsp商品列表页面显示
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head><title>首页</title><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link type="text/css" rel="stylesheet" href="css/bootstrap.css"><link type="text/css" rel="stylesheet" href="css/style.css"><script type="text/javascript" src="js/jquery.min.js"></script><script type="text/javascript" src="js/bootstrap.min.js"></script><script type="text/javascript" src="layer/layer.js"></script><script type="text/javascript" src="js/cart.js"></script>
</head>
<body><jsp:include page="header.jsp"><jsp:param name="flag" value="2"></jsp:param>
</jsp:include><div class="products"><div class="container"><h2><c:choose><c:when test="${empty t}">全部系列</c:when><c:otherwise>${t.name}</c:otherwise> </c:choose></h2><div class="col-md-12 product-model-sec"><c:forEach items="${p.list}" var="g"><div class="product-grid"><a href="/goods_detail?id=${g.id}"><div class="more-product"><span> </span></div><div class="product-img b-link-stripe b-animate-go thickbox"><img src="${g.cover}" class="img-responsive" alt="${g.name}" width="240" height="240"><div class="b-wrapper"><h4 class="b-animate b-from-left b-delay03"><button href="/goods_detail?id=${g.id}">查看详情</button></h4></div></div></a><div class="product-info simpleCart_shelfItem"><div class="product-info-cust prt_name"><h4>${g.name}</h4><span class="item_price">¥ ${g.price}</span><input type="button" class="item_add items" value="加入购物车" onclick="buy(${g.id})"><div class="clearfix"> </div></div></div></div></c:forEach></div><jsp:include page="page.jsp"><jsp:param name="url" value="/goods_list"></jsp:param><jsp:param name="param" value="&typeid=${id}"></jsp:param></jsp:include></div></div>
</div><jsp:include page="footer.jsp"></jsp:include></body>
</html>
该页面中需要显示分页,因此这里把分页的显示抽离成page.jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<div style='text-align:center;'><a class='btn btn-info' <c:if test="${p.pageNumber==1 }">disabled</c:if> <c:if test="${p.pageNumber!=1 }">href="${param.url }?pageNumber=1${param.param }"</c:if>>首页</a><a class='btn btn-info' <c:if test="${p.pageNumber==1 }">disabled</c:if> <c:if test="${p.pageNumber!=1 }">href="${pageContext.request.contextPath }${param.url }?pageNumber=${p.pageNumber-1}${param.param }"</c:if>>上一页</a><h3 style='display:inline;'>[${p.pageNumber }/${p.totalPage }]</h3><h3 style='display:inline;'>[${p.totalCount }]</h3><a class='btn btn-info' <c:if test="${p.totalPage==0 || p.pageNumber==p.totalPage }">disabled</c:if> <c:if test="${p.pageNumber!=p.totalPage }">href="${param.url }?pageNumber=${p.pageNumber+1}${param.param }"</c:if>>下一页</a><a class='btn btn-info' <c:if test="${p.totalPage==0 || p.pageNumber==p.totalPage }">disabled</c:if> <c:if test="${p.pageNumber!=p.totalPage }">href="${param.url }?pageNumber=${p.totalPage}${param.param }"</c:if>>尾页</a><input type='text' class='form-control' style='display:inline;width:60px;' value=''/><a class='btn btn-info' href='javascript:void(0);' onclick='location.href="${param.url }?pageNumber="+(this.previousSibling.value)+"${param.param }"'>GO</a>
</div>
这篇关于【JavaWeb】网上蛋糕项目商城-商品分类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!