美文网首页
商品管理案例——实现分类管理模块

商品管理案例——实现分类管理模块

作者: 嗷老板 | 来源:发表于2018-04-10 21:16 被阅读0次

商品分类的JavaBean

package com.itheima.domain;

import java.io.Serializable;

public class Category implements Serializable{
    private Integer cid;
    private String cname;
    private String description;

    public Category() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Category(Integer cid, String cname, String description) {
        super();
        this.cid = cid;
        this.cname = cname;
        this.description = description;
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

添加分类的jsp页面

  在这个页面中我们需要创建一个表单用于提交商品分类的信息,并且在提交的时候检验用户名是否为空。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@include file="/manage/header.jsp" %>
    <!-- 添加用户名不为空的校验 -->
    <script type="text/javascript">
        function checkName(){
            var cname = $("input[name=cname]").val();
            if(cname == ""){
                $("span").html("分类名称不能为空!");
                return false;
            }
            
            return true;
        }
    
    
        $(function(){
            $("form").submit(function(){
                return checkName();
            });
        });
    </script>
    
    
    
    <form action="${pageContext.request.contextPath }/CategoryServlet" method="post">
        <!-- 这里设置一个表单的隐藏项是为了让服务器知道这个页面的作用,但是不需要让用户看到 -->
        <input type="hidden" name="op" value="add"/>
        <table style="width:500px;">
            <tr>
            <td>分类名称:</td><td><input type="text" name="cname"/><span></span></td>
            </tr>
            <tr>
            <td>分类描述:</td><td><textarea name="description" row="3"></textarea></td>
            </tr>
            <tr>
            <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>
        
    </form>
    
</body>
</html>

查看分类的listCategory.jsp

  这个页面用于展示商品分类的信息,并实现对分类的删除和修改的功能。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/manage/header.jsp" %>

    <script type="text/javascript">
        function confirmDel(cid){
            var flag = window.confirm("确认删除分类?");
            
            if(flag){
                //用户确定删除
                window.location = "${pageContext.request.contextPath}/CategoryServlet?op=del&cid=" + cid;
            }
        }
    </script>


    <table style="width: 400px;">
        <tr>
            <td>分类名称</td>
            <td>分类描述</td>
            <td>操作</td>
        </tr>
        <c:forEach var="c" items="${cs }">
            <tr>
                <td>${c.cname }</td>
                <td>${c.description}</td>
                <td>[<a href="#" onclick="confirmDel(${c.cid});" >删除</a>|<a href="${pageContext.request.contextPath }/CategoryServlet?op=findById&cid=${c.cid}">修改</a>]</td>
            </tr>
        </c:forEach>
    </table>
    
</body>
</html>

修改商品分类信息的editCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@include file="/manage/header.jsp" %>
    <!-- 添加用户名不为空的校验 -->
    <script type="text/javascript">
        function checkName(){
            var cname = $("input[name=cname]").val();
            if(cname == ""){
                $("span").html("分类名称不能为空!");
                return false;
            }
            
            return true;
        }
    
    
        $(function(){
            $("form").submit(function(){
                return checkName();
            });
        });
    </script>
    
    
    
    <form action="${pageContext.request.contextPath }/CategoryServlet" method="post">
        <!-- 这里设置一个表单的隐藏项是为了让服务器知道这个页面的作用,但是不需要让用户看到 -->
        <input type="hidden" name="op" value="edit"/>
        <input type="hidden" name="cid" value="${c.cid}"/>
        
        <table style="width:500px;">
            <tr>
            <td>分类名称:</td><td><input type="text" name="cname" value="${c.cname }"/><span></span></td>
            </tr>
            <tr>
            <td>分类描述:</td><td><textarea name="description" row="3" >${c.description}</textarea></td>
            </tr>
            <tr>
            <td colspan="2"><input type="submit" value="提交"/></td>
            </tr>
        </table>
        
    </form>
    
</body>
</html>

服务器端的CategoryServlet

  在CategoryServlet中对商品管理系统的各个功能进行区分,然后传入相应的业务逻辑层。在Servlet中还对所有的异常进行了处理。

package com.itheima.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 org.apache.commons.beanutils.BeanUtils;

import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
import com.itheima.service.impl.CategoryServiceImpl;

public class CategoryServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取页面中隐藏表单项的属性
        String op = request.getParameter("op");
        
        //判断页面的作用
        if("add".equals(op)){
            //如果是添加分类的页面,则调用addCategory方法
            addCategory(request,response);
        }else if("find".equals(op)){
            findCategory(request,response);
        }else if("del".equals(op)){
            delCategory(request,response);
        }else if("findById".equals(op)){
            findByIdCategory(request,response);
        }else if("edit".equals(op)){
            updateCategory(request,response);
        }
    }

    private void updateCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            Category c = new Category();
            BeanUtils.populate(c, request.getParameterMap());
            
            CategoryService service = new CategoryServiceImpl();
            service.updateCategory(c);
            
            request.setAttribute("msg", "添加成功!<a href='"+request.getContextPath()+"/CategoryServlet?op=find'>继续查看</a>");
            request.getRequestDispatcher("/manage/message.jsp").forward(request, response);
            return;
        } catch (Exception e) {
            // 如果抛出异常,说明添加失败,返回提示信息
            e.printStackTrace();
            request.setAttribute("msg", "修改分类失败!请联系管理员!");
            request.getRequestDispatcher("/manage/message.jsp").forward(request, response);
            return;
        } 
        
    }

    private void findByIdCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取要修改的分类id
        String id = request.getParameter("cid");
        Integer cid = new Integer(id);
        
        //传入业务逻辑
        try {
            CategoryService service = new CategoryServiceImpl();
            Category c = service.findByIdCategory(cid);
            
            request.setAttribute("c", c);
            request.getRequestDispatcher("manage/editCategory.jsp").forward(request, response);
            return;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            request.setAttribute("msg", "查询除分类失败!请联系管理员!");
            request.getRequestDispatcher("/manage/message.jsp").forward(request, response);
            return;
        }
        
    }

    private void delCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取要删除商品的id
        String id = request.getParameter("cid");
        Integer cid = new Integer(id);
        
        //将需要删除的分类信息传给业务逻辑层
        try {
            CategoryService service = new CategoryServiceImpl();
            service.delCategory(cid);
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            request.setAttribute("msg", "删除分类失败!请联系管理员!");
            request.getRequestDispatcher("/manage/message.jsp").forward(request, response);
            return;
        }
        
        //删除完成后,再次显示分类信息
        findCategory(request,response);
        return;
        
    }

    private void findCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        try {
            CategoryService service = new CategoryServiceImpl();
            List<Category> list = service.findCategory();
            
            request.setAttribute("cs", list);
            request.getRequestDispatcher("/manage/listCategory.jsp").forward(request, response);
            return;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            request.setAttribute("msg", "查询分类失败!请联系管理员!");
            request.getRequestDispatcher("/manage/message.jsp").forward(request, response);
            return;
        }
        
    }

    //添加分类
    private void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建Category对象
        try {
            Category c = new Category();
            BeanUtils.populate(c, request.getParameterMap());
            
            CategoryService service = new CategoryServiceImpl();
            service.addCategory(c);
        } catch (Exception e) {
            // 如果抛出异常,说明添加失败,返回提示信息
            e.printStackTrace();
            request.setAttribute("msg", "添加分类失败!请联系管理员!");
            request.getRequestDispatcher("/manage/message.jsp").forward(request, response);
            return;
        } 
        
        request.setAttribute("msg", "添加分类成功!<a href='"+request.getContextPath()+"/manage/addCategory.jsp'>继续添加</a>");
        request.getRequestDispatcher("/manage/message.jsp").forward(request, response);
        return;
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

业务逻辑层的接口和实现类

  为了提高代码的复用性,我们使用面向接口编程的思想,创建接口CategoryService接口和CategoryServiceImpl实现类,对业务的逻辑进行处理,然后传入数据处理层进行处理。
接口CategoryService

package com.itheima.service;

import java.sql.SQLException;
import java.util.List;

import com.itheima.domain.Category;

public interface CategoryService {

    public void addCategory(Category c) throws SQLException;

    public List<Category> findCategory() throws SQLException;

    public void delCategory(Integer cid) throws SQLException;

    public Category findByIdCategory(Integer cid) throws Exception;

    public void updateCategory(Category c) throws SQLException;

}

实现类CategoryServiceImpl

package com.itheima.service.impl;

import java.sql.SQLException;
import java.util.List;

import com.itheima.dao.CategoryDao;
import com.itheima.dao.impl.CategoryDaoImpl;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;

public class CategoryServiceImpl implements CategoryService {

    @Override
    public void addCategory(Category c) throws SQLException {
        // 将数据传入数据访问层添加到数据库中
        CategoryDao dao = new CategoryDaoImpl();
        dao.addCategory(c);

    }

    @Override
    public List<Category> findCategory() throws SQLException {
        CategoryDao dao = new CategoryDaoImpl();
        
        return dao.findCategory();
    }

    @Override
    public void delCategory(Integer cid) throws SQLException {
        CategoryDao dao = new CategoryDaoImpl();
        dao.delCategory(cid);
        
    }

    @Override
    public Category findByIdCategory(Integer cid) throws Exception {
        CategoryDao dao = new CategoryDaoImpl();
        Category c = dao.findByInCategory(cid);
        
        if(c == null){
            throw new Exception();
        }
        return c;
    }

    @Override
    public void updateCategory(Category c) throws SQLException {
        CategoryDao dao = new CategoryDaoImpl();
        dao.updateCategory(c);
        
    }

}

数据处理层的接口和实现类

  我们在这里同样使用面向接口编程的思想,创建接口CategoryDao接口和CategoryDaoImpl实现类,对数据库中的数据进行处理。
接口CategoryDao

package com.itheima.dao;

import java.sql.SQLException;
import java.util.List;

import com.itheima.domain.Category;

public interface CategoryDao {

    public void addCategory(Category c) throws SQLException;

    public List<Category> findCategory() throws SQLException;

    public void delCategory(Integer cid) throws SQLException;

    public Category findByInCategory(Integer cid) throws Exception;

    public void updateCategory(Category c) throws SQLException;

}

实现类CategoryDaoImpl

package com.itheima.dao.impl;

import java.sql.SQLException;
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 com.itheima.dao.CategoryDao;
import com.itheima.domain.Category;
import com.itheima.utils.JDBCUtils;

public class CategoryDaoImpl implements CategoryDao {

    @Override
    public void addCategory(Category c) throws SQLException {
        //连接数据库,添加数据
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        qr.update("insert into category (cname,description) values (?,?)",c.getCname(),c.getDescription());

    }

    @Override
    public List<Category> findCategory() throws SQLException {
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        return qr.query("select * from category", new BeanListHandler<Category>(Category.class));
    }

    @Override
    public void delCategory(Integer cid) throws SQLException {
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        qr.update("delete from category where cid = ?",cid);
    }

    @Override
    public Category findByInCategory(Integer cid) throws Exception {
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        return qr.query("select * from category where cid = ?", new BeanHandler<Category>(Category.class),cid);
        
    }

    @Override
    public void updateCategory(Category c) throws SQLException {
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
        qr.update("update category set cname=?,description=? where cid = ?",c.getCname(),c.getDescription(),c.getCid());
    }

}

案例展示

首页

添加分类功能

添加分类
添加分类成功

查询分类

查询分类

删除分类

删除分类
删除成功

修改分类

修改分类
修改成功

相关文章

网友评论

      本文标题:商品管理案例——实现分类管理模块

      本文链接:https://www.haomeiwen.com/subject/yixohftx.html