【JavaWeb】网上蛋糕项目商城-商品分类

2024-05-05 17:20

本文主要是介绍【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】网上蛋糕项目商城-商品分类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/962245

相关文章

Spring Boot整合Redis注解实现增删改查功能(Redis注解使用)

《SpringBoot整合Redis注解实现增删改查功能(Redis注解使用)》文章介绍了如何使用SpringBoot整合Redis注解实现增删改查功能,包括配置、实体类、Repository、Se... 目录配置Redis连接定义实体类创建Repository接口增删改查操作示例插入数据查询数据删除数据更

Java Lettuce 客户端入门到生产的实现步骤

《JavaLettuce客户端入门到生产的实现步骤》本文主要介绍了JavaLettuce客户端入门到生产的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目录1 安装依赖MavenGradle2 最小化连接示例3 核心特性速览4 生产环境配置建议5 常见问题

Java使用Swing生成一个最大公约数计算器

《Java使用Swing生成一个最大公约数计算器》这篇文章主要为大家详细介绍了Java使用Swing生成一个最大公约数计算器的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下... 目录第一步:利用欧几里得算法计算最大公约数欧几里得算法的证明情形 1:b=0情形 2:b>0完成相关代码第二步:加

Java 的ArrayList集合底层实现与最佳实践

《Java的ArrayList集合底层实现与最佳实践》本文主要介绍了Java的ArrayList集合类的核心概念、底层实现、关键成员变量、初始化机制、容量演变、扩容机制、性能分析、核心方法源码解析、... 目录1. 核心概念与底层实现1.1 ArrayList 的本质1.1.1 底层数据结构JDK 1.7

Java Map排序如何按照值按照键排序

《JavaMap排序如何按照值按照键排序》该文章主要介绍Java中三种Map(HashMap、LinkedHashMap、TreeMap)的默认排序行为及实现按键排序和按值排序的方法,每种方法结合实... 目录一、先理清 3 种 Map 的默认排序行为二、按「键」排序的实现方式1. 方式 1:用 TreeM

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node