javaWeb实战教程9-商品分类模块的编码实现

来源:互联网 发布:保留小数位数的函数sql 编辑:程序博客网 时间:2024/06/05 03:33

javaWeb实战教程


6.商品分类模块的开发

商品分类比较简单,在前台主要是展示作用。根据数据库在包fy.test.model里新建Clasz.java:

public class Clasz {    private int id;    private String name;    private int 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 int getType() {        return type;    }    public void setType(int type) {        this.type = type;    }}

Clasz类的字段type是大分类,大分类有四个:休闲食品、粮油米面、山珍特产、中外名酒,对应type取值分别是1,2,3,4。


在包fy.test.dao里新建类ClaszDao.java,创建全局变量private Connection connection;;创建方法根据type值取Type列表:

public List<Clasz> getListByType(int type) throws SQLException {    return new QueryRunner().query(connection, "select * from clasz where type=?",            new BeanListHandler<>(Clasz.class), type);}

在包fy.test.service里新建ClaszService.java,同样创建方法:

public List<Clasz> getListByType(int type) {    Connection connection = DBUtil.getConnection();    try {        claszDao.setConnection(connection);        if (type < 0)            return claszDao.getList();        else            return claszDao.getListByType(type);    } catch (Exception e) {        throw new RuntimeException(e);    } finally {        DBUtil.close(connection);    }}

这个在线商城没有分类的展示页面,分类只存在于每个页面的页头菜单里;在编写用户模块时,我们将页头单独写成了一个header.jsp页面,为了让每一个页面的页头都能读取到分类信息,我们把分类的数据使用过滤器直接写进request里。

在包fy.test.filter里新建过滤器LoadHeaderDataFilter.java,在doFilter方法里把所有的分类都读取进request:

@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {    request.setAttribute("claszes1", claszService.getListByType(1));    request.setAttribute("claszes2", claszService.getListByType(2));    request.setAttribute("claszes3", claszService.getListByType(3));    request.setAttribute("claszes4", claszService.getListByType(4));    chain.doFilter(request, response);}

改造head.jsp页面,将分类展示在页面上:

<div class="box">    <div class="title">休闲食品</div>    <div class="link">        <c:forEach items="${claszes1}" var="c"><a href="product/list?claszId=${c.id }">${c.name}</a></c:forEach>    </div></div><div class="box">    <div class="title">粮油米面</div>    <div class="link">        <c:forEach items="${claszes2}" var="c"><a href="product/list?claszId=${c.id }">${c.name}</a></c:forEach>    </div></div><div class="box">    <div class="title">山珍特产</div>    <div class="link">        <c:forEach items="${claszes3}" var="c"><a href="product/list?claszId=${c.id }">${c.name}</a></c:forEach>    </div></div><div class="box">    <div class="title">中外名酒</div>    <div class="link">        <c:forEach items="${claszes4}" var="c"><a href="product/list?claszId=${c.id }">${c.name}</a></c:forEach>    </div></div>

在数据库的商品分类表上随便加几个数据,查看最终效果。

原创粉丝点击