一、分类的根据id删除
分析sql:
delete from category where cid = ?
传参:cid
代码实现:
category_list.jsp
<a href="javascript:void(0)" onclick="delByCid(${c.cid})" >删除</a><script>//删除分类function delByCid(cid){if(confirm("是否确定删除呢?")){location.href = "/xm/category?method=delByCid&cid="+cid;}}</script>
Servlet:
protected void delByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1、获取数据String cid = request.getParameter("cid");//2、调用业务CategoryService cs = new CategoryService();int row = cs.delByCid(cid);//3、结果展示if(row >0) {//删除成功response.sendRedirect("/xm/category?method=selectClistByPage&pageNumber=1");}else {response.getWriter().write("删除分类失败!!");}}
Service:
public int delByCid(String cid) {// TODO Auto-generated method stubreturn cd.delByCid(cid);}
Dao:
public int delByCid(String cid) {String sql = "delete from category where cid = ?";try {return qr.update(sql, cid);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return 0;}}
二、商品模块的环境准备
表结构:
CREATE TABLE `product` (`pid` INT(10) PRIMARY KEY AUTO_INCREMENT, #主键 自增`pname` VARCHAR(50) NOT NULL,#商品名称`color` VARCHAR(50),#商品颜色`price` DOUBLE NOT NULL,#价格`description` VARCHAR(500),#描述`pic` VARCHAR(200), # 图片`state` INT(5) DEFAULT '0',#0:普通 1:热门产品 2:为你推荐 3:新品 4:小米明星单品`version` VARCHAR(50), # 型号`product_date` DATETIME, # 生产日期cid INT(10) # 所属分类的主键) ;
表关系:
- 一对多、多对一(分类和商品)
- 多对多(演员和角色)
- 一对一(丈夫和妻子)
页面结构:
product_list.jsp : 商品列表展示product_add.jsp:添加
product_update.jsp:修改
包结构:
pojo、servlet、service、dao
三:商品模块的分页查询
思路分析:

代码实现:略
Product:
public class Product {private Category category;..}
Service:
public PageBean<Product> selectPistByPage(PageBean<Product> pb) {//1、查询当前页的数据List<Product> result = pd.selectPlistByPage(pb);for(Product p : result) {//获取cid的值int cid = p.getCid();Category category = cd.selectByCid(cid+"");p.setCategory(category);}pb.setResult(result);//2、查询总记录数int totalCount = pd.selectCount();pb.setTotalCount(totalCount);return pb;}
product_list取出分类名称:
<td>${p.category.cname}</td>
四、添加商品
1、跳转到添加商品页面
问题:直接跳转还是走数据库查询然后跳转?
因为跳转到添加页面时,需要回显所有分类名称,所以需要查询数据库
分析sql:
select * from category
代码实现:
product_list.jsp
<li onclick="toAdd()" style="cursor: pointer;" id="addProduct" ><span><img src="${pageContext.request.contextPath}/admin/images/t01.png" /></span>添加商品</li><script type="text/javascript">//跳转到添加商品页面function toAdd(){location.href = "/xm/product?method=toAdd";}</script>
Servlet:
//跳转到添加商品页面protected void toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1、获取数据(暂无)//2、调用业务CategoryService cs = new CategoryService();List<Category> clist = cs.selectClist();//3、结果的展示request.setAttribute("clist", clist);request.getRequestDispatcher("/admin/product_add.jsp").forward(request, response);}
Service:
public List<Category> selectClist() {// TODO Auto-generated method stubreturn cd.selectClist();}
Dao:
public List<Category> selectClist() {String sql = "select * from category";try {return qr.query(sql,new BeanListHandler<Category>(Category.class));} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}
product_add.jsp
<!-- 商品分类信息 --><li><label>商品分类</label><select name="cid" class="dfinput"><option value="0">===请选择===</option><c:if test="${not empty clist}"><c:forEach items="${clist}" var="c"><option value="${c.cid}">${c.cname}</option></c:forEach></c:if></select></li>
2、添加商品
思路:
页面:
文件上传:file、post、enctype
Servlet:
获取所有参数列表、使用BeanUtils封装到product对象中@MultipartCongfig、getPart()、writerpic字段存什么值
代码:参考用户注册
五、网站前台首页—头部的显示
目前:访问的项目路径名写死了 ,如果后期更改了项目名,那么所有涉及之前项目名路径的地方都要进行修改
解决:动态获取项目名
- Servlet:String contextPath = request.getContextPath();
- Jsp:${pageContext.request.contextPath}
登录的两种情况:
用户未登录:
显示 : 登录、注册 提示用户去注册登录
用户已登录:
显示:欢迎您:xxx
如何判断用户是否登录了呢? 登录后将用户信息存到session中
代码:
UserService中登录成功将用户信息存到session中:
if(code != null && (phoneNumber+code).equals(sessionCode)) {//3、登录成功request.getSession().setAttribute("qianUser", user);return "2";}
index.jsp中进行判断:
<c:if test="${empty qianUser}"><a class="mix" href="${pageContext.request.contextPath}/login.jsp">登录 </a><a href="${pageContext.request.contextPath}/register.jsp">注册</a></c:if><c:if test="${not empty qianUser}"><span><font color="red">欢迎您:${qianUser.username}</font> </span></c:if>
六、动态查询分类名称显示在首页
思路:
登录成功----请求服务器从数据库中将所有分类查出来-----跳转到index.jsp-----取出数据
分析sql:
需求:展示的效果要进行排序,根据order_number 从小到大进行排序
select * from category order by order_number asc;
代码实现:
login.jsp 登录成功请求Servlet
else if(msg == "2"){//$("#msg").html("登录成功!!");//跳转到index.jsp//location.href = "${pageContext.request.contextPath}/index.jsp";location.href = "${pageContext.request.contextPath}/category?method=selectClist";}
Servlet:
//查询所有分类protected void selectClist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1、获取数据//2、调用业务CategoryService cs = new CategoryService();List<Category> clist = cs.selectClist();//3、结果展示request.setAttribute("clist", clist);request.getRequestDispatcher("/index.jsp").forward(request, response);}
Service:
public List<Category> selectClist() {// TODO Auto-generated method stubreturn cd.selectClist();}
Dao:
public List<Category> selectClist() {String sql = "select * from category order by order_number asc";try {return qr.query(sql,new BeanListHandler<Category>(Category.class));} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}
index.jsp:
<!--动态展示 --><c:if test="${not empty clist}"><c:forEach items="${clist}" var ="category"><li class="scr_li"><a href="">${category.cname}</a><i class="scr_i"></i></li></c:forEach></c:if>
问题:用户直接访问index.jsp时,不显示分类名称?
解决思路:
- 在第一个用户访问index.jsp之前就 存好了分类信息
- 服务器启动时查询分类名称,存到域对象中(如何做到??)
监听器Listener:监听到某种行为就采取某种操作
某种行为:服务器启动时采取操作:执行方法查询分类信息
代码实现:
监听器:作用 服务器启动时执行
@WebListenerpublic class MyListener implements ServletContextListener {public void contextDestroyed(ServletContextEvent arg0) {}//服务器启动时执行public void contextInitialized(ServletContextEvent sce) {//查询分类信息CategoryService cs = new CategoryService();List<Category> clist = cs.selectClist();//3、结果展示sce.getServletContext().setAttribute("clist", clist);}}
login.jsp 登录成功直接跳转到index.jsp
location.href = "${pageContext.request.contextPath}/index.jsp";
七、查询小米明星单品(前五条)
分析sql:
select * from product where state = 4 limit 0,5;
代码实现:
MyListener:
ProductService ps = new ProductService();List<Product> plist = ps.selectStarPlist();sce.getServletContext().setAttribute("starList", plist);
Service:
public List<Product> selectStarPlist() {// TODO Auto-generated method stubreturn pd.selectStarPlist();}
Dao:
public List<Product> selectStarPlist() {String sql = "select * from product where state = 4 limit 0,5;";try {return qr.query(sql, new BeanListHandler<Product>(Product.class));} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}
八、点击商品跳转到商品详情页面
product_detail.jsp 负责商品数据的回显
分析sql:
select * from product where pid = ?
index.jsp
<a href="${pageContext.request.contextPath}/product?method=toProductDetail&pid=${star.pid}" target="_blank"><img class="time_min" style="width:234px;height: 234px;" src="/xm_upload/${star.pic}" alt=""></a>
Servlet:
//跳转到商品详情页面protected void toProductDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String pid = request.getParameter("pid");ProductService ps = new ProductService();Product product = ps.selectByPid(pid);request.setAttribute("product", product);request.getRequestDispatcher("/product_detail.jsp").forward(request, response);}
Service:
public Product selectByPid(String pid) {// TODO Auto-generated method stubreturn pd.selectByPid(pid);}
Dao:
public Product selectByPid(String pid) {String sql = "select * from product where pid = ?";try {return qr.query(sql, new BeanHandler<Product>(Product.class),pid);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}
prodcut_detail.jsp
略
九、购物车分析&实现
如何封装购物车相关的数据:
思路:
- 目标:在购物车页面进行数据的展示
- 如果要进行数据展示:封装pojo中的JavaBean
- 如何封装数据:根据已有的购物车页面分析

JavaBean封装的实现:
//购物项public class CartItem {//商品private Product product;//购买数量private int count;//小计private double subTotal;//计算小计public double getSubTotal() {return subTotal = (getProduct().getPrice())*getCount();}....}
//购物车public class Cart {/** 问题:用什么集合存CartItem对象** 需求:* 1、购物车中的商品是有序的* 2、移除购物车方便** Set:无序不可重复 pass* List:有序可以重复 删除不方便 pass* Map<key,value> remove(key) LinkedHashMap(选它)* key:pid* value:CartIem* */private Map<Integer,CartItem> cartmap = new LinkedHashMap<Integer,CartItem>();//总价格private double total;//计算总价格public double getTotal() {total = 0.0;Set<Integer> keys = cartmap.keySet();for(Integer key:keys) {CartItem cartItem = cartmap.get(key);total += cartItem.getSubTotal();}return total;}....}
逻辑分析:
点加入购物车按钮时,要传什么参数过去:
pid、购买数量count
业务:将购物项对象加入到购物车对象中
- 购物项对象
- 购物车对象
- 将购物项对象添加到购物车中
