1. 程式人生 > >JAVAEE——SSH項目實戰02:客戶列表和BaseDao封裝

JAVAEE——SSH項目實戰02:客戶列表和BaseDao封裝

nbsp jstl n) top 默認 ica ring put ava

作者: kent鵬

轉載請註明出處: http://www.cnblogs.com/xieyupeng/p/7129152.html

該項目在SSH三大框架整合基礎上進行開發:http://www.cnblogs.com/xieyupeng/p/7108141.html

一、客戶列表

  1.分析

技術分享

  2.書寫步驟

  (1)封裝PageBean

public class PageBean {
    //當前頁數
    private Integer currentPage;
    //總記錄數
    private Integer totalCount;
    //每頁顯示條數
    private Integer pageSize;
    
//總頁數 private Integer totalPage; //分頁列表數據 private List list; public PageBean(Integer currentPage, Integer totalCount, Integer pageSize) { this.totalCount = totalCount; this.pageSize = pageSize; this.currentPage = currentPage;
if(this.currentPage == null){ //如頁面沒有指定顯示那一頁.顯示第一頁. this.currentPage = 1; } if(this.pageSize == null){ //如果每頁顯示條數沒有指定,默認每頁顯示3條 this.pageSize = 3; } //計算總頁數 this.totalPage = (this.totalCount+this.pageSize-1)/this
.pageSize; //判斷當前頁數是否超出範圍 //不能小於1 if(this.currentPage < 1){ this.currentPage = 1; } //不能大於總頁數 if(this.currentPage > this.totalPage){ this.currentPage = this.totalPage; } } //計算起始索引 public int getStart(){ return (this.currentPage-1)*this.pageSize; } public Integer getCurrentPage() { return currentPage; } public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getTotalPage() { return totalPage; } public void setTotalPage(Integer totalPage) { this.totalPage = totalPage; } public List getList() { return list; } public void setList(List list) { this.list = list; } }

  (2)書寫Action

public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {
    private Customer customer = new Customer();
    
    private CustomerService cs;

    private Integer currentPage;
    private Integer pageSize;
    public String list() throws Exception {
        //封裝離線查詢對象
        DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
        //判斷並封裝參數
        if(StringUtils.isNotBlank(customer.getCust_name())){
            dc.add(Restrictions.like("cust_name", "%"+customer.getCust_name()+"%"));
        }
        
        //1 調用Service查詢分頁數據(PageBean)
        PageBean pb = cs.getPageBean(dc,currentPage,pageSize);
        //2 將PageBean放入request域,轉發到列表頁面顯示
        ActionContext.getContext().put("pageBean", pb);
        return "list";
    }

    @Override
    public Customer getModel() {
        return customer;
    }

    public void setCs(CustomerService cs) {
        this.cs = cs;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

}

  (3)書寫Service

public class CustomerServiceImpl implements CustomerService {
    private CustomerDao cd;
    @Override
    public PageBean getPageBean(DetachedCriteria dc, Integer currentPage, Integer pageSize) {
        //1 調用Dao查詢總記錄數
        Integer totalCount = cd.getTotalCount(dc);
        //2 創建PageBean對象
        PageBean pb = new PageBean(currentPage, totalCount, pageSize);
        //3 調用Dao查詢分頁列表數據
        
        List<Customer> list = cd.getPageList(dc,pb.getStart(),pb.getPageSize());
        //4 列表數據放入pageBean中.並返回
        pb.setList(list);
        return pb;
    }
    public void setCd(CustomerDao cd) {
        this.cd = cd;
    }

}

  (4)書寫Dao

public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {

    public Integer getTotalCount(DetachedCriteria dc) {
        //設置查詢的聚合函數,總記錄數
        dc.setProjection(Projections.rowCount());
        
        List<Long> list = (List<Long>) getHibernateTemplate().findByCriteria(dc);
        
        //清空之前設置的聚合函數
        dc.setProjection(null);
        
        if(list!=null && list.size()>0){
            Long count = list.get(0);
            return count.intValue();
        }else{
            return null;
        }
    }

    public List<Customer> getPageList(DetachedCriteria dc, int start, Integer pageSize) {
        
        return (List<Customer>) getHibernateTemplate().findByCriteria(dc, start, pageSize);

    }

}

  (5)完成struts以及spring的配置

   strus.xml添加代碼:

    <action name="CustomerAction_*" class="customerAction" method="{1}" >
         <result name="list"  >/jsp/customer/list.jsp</result>
    </action>

   applicationContext.xml添加代碼:

    <bean name="customerAction" class="cn.xyp.web.action.CustomerAction" scope="prototype" >
        <property name="cs" ref="customerService" ></property>
    </bean>

    <bean name="customerService" class="cn.xyp.service.impl.CustomerServiceImpl" >
        <property name="cd" ref="customerDao" ></property>
    </bean>

    <bean name="customerDao" class="cn.xyp.dao.impl.CustomerDaoImpl" >
        <!-- 註入sessionFactory -->
        <property name="sessionFactory" ref="sessionFactory" ></property>
    </bean>

  (6)書寫前臺list.jsp頁面

   主要通過表單提交隱藏域的數據、jq和ognl表達式來實現。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib  prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<TITLE>客戶列表</TITLE> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<LINK href="${pageContext.request.contextPath }/css/Style.css" type=text/css rel=stylesheet>
<LINK href="${pageContext.request.contextPath }/css/Manage.css" type=text/css
    rel=stylesheet>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<SCRIPT language=javascript>
    function changePage(pageNum){
            //1 將頁碼的值放入對應表單隱藏域中
                $("#currentPageInput").val(pageNum);
            //2 提交表單
                $("#pageForm").submit();
    };
    
    function changePageSize(pageSize){
            //1 將頁碼的值放入對應表單隱藏域中
            $("#pageSizeInput").val(pageSize);
        //2 提交表單
            $("#pageForm").submit();
    };
</SCRIPT>

<META content="MSHTML 6.00.2900.3492" name=GENERATOR>
</HEAD>
<BODY>

        <TABLE cellSpacing=0 cellPadding=0 width="98%" border=0>
            <TBODY>
                <TR>
                    <TD width=15><IMG src="${pageContext.request.contextPath }/images/new_019.jpg"
                        border=0></TD>
                    <TD width="100%" background="${pageContext.request.contextPath }/images/new_020.jpg"
                        height=20></TD>
                    <TD width=15><IMG src="${pageContext.request.contextPath }/images/new_021.jpg"
                        border=0></TD>
                </TR>
            </TBODY>
        </TABLE>
        <TABLE cellSpacing=0 cellPadding=0 width="98%" border=0>
            <TBODY>
                <TR>
                    <TD width=15 background=${pageContext.request.contextPath }/images/new_022.jpg><IMG
                        src="${pageContext.request.contextPath }/images/new_022.jpg" border=0></TD>
                    <TD vAlign=top width="100%" bgColor=#ffffff>
                        <TABLE cellSpacing=0 cellPadding=5 width="100%" border=0>
                            <TR>
                                <TD class=manageHead>當前位置:客戶管理 &gt; 客戶列表</TD>
                            </TR>
                            <TR>
                                <TD height=2></TD>
                            </TR>
                        </TABLE>
                        <TABLE borderColor=#cccccc cellSpacing=0 cellPadding=0
                            width="100%" align=center border=0>
                            <TBODY>
                                <TR>
                                    <TD height=25>
                                    <FORM id="pageForm" name="customerForm"
                                        action="${pageContext.request.contextPath }/CustomerAction_list"
                                        method=post>
                                        <!-- 隱藏域.當前頁碼 -->
                                        <input type="hidden" name="currentPage" id="currentPageInput" value="<s:property value="#pageBean.currentPage" />" />
                                        <!-- 隱藏域.每頁顯示條數 -->
                                        <input type="hidden" name="pageSize" id="pageSizeInput"       value="<s:property value="#pageBean.pageSize" />" />
                                        <TABLE cellSpacing=0 cellPadding=2 border=0>
                                            <TBODY>
                                                <TR>
                                                    <TD>客戶名稱:</TD>
                                                    <TD><INPUT class=textbox id=sChannel2
                                                        style="WIDTH: 80px" maxLength=50 name="cust_name" value="${param.cust_name}"></TD>
                                                    
                                                    <TD><INPUT class=button id=sButton2 type=submit
                                                        value=" 篩選 " name=sButton2></TD>
                                                </TR>
                                            </TBODY>
                                        </TABLE>
                                    </FORM>
                                    </TD>
                                </TR>
                                
                                <TR>
                                    <TD>
                                        <TABLE id=grid
                                            style="BORDER-TOP-WIDTH: 0px; FONT-WEIGHT: normal; BORDER-LEFT-WIDTH: 0px; BORDER-LEFT-COLOR: #cccccc; BORDER-BOTTOM-WIDTH: 0px; BORDER-BOTTOM-COLOR: #cccccc; WIDTH: 100%; BORDER-TOP-COLOR: #cccccc; FONT-STYLE: normal; BACKGROUND-COLOR: #cccccc; BORDER-RIGHT-WIDTH: 0px; TEXT-DECORATION: none; BORDER-RIGHT-COLOR: #cccccc"
                                            cellSpacing=1 cellPadding=2 rules=all border=0>
                                            <TBODY>
                                                <TR
                                                    style="FONT-WEIGHT: bold; FONT-STYLE: normal; BACKGROUND-COLOR: #eeeeee; TEXT-DECORATION: none">
                                                    <TD>客戶名稱</TD>
                                                    <TD>客戶級別</TD>
                                                    <TD>客戶來源</TD>
                                                    <TD>聯系人</TD>
                                                    <TD>電話</TD>
                                                    <TD>手機</TD>
                                                    <TD>操作</TD>
                                                </TR>
                                                <s:iterator value="#pageBean.list" var="cust" >
                                                <TR         
                                                    style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none">
                                                    <TD>
                                                        <s:property value="#cust.cust_name" />
                                                    </TD>
                                                    <TD>
                                                    <s:property value="#cust.cust_level" />
                                                    </TD>
                                                    <TD>
                                                    <s:property value="#cust.cust_source" />
                                                    </TD>
                                                    <TD>
                                                    <s:property value="#cust.cust_linkman" />
                                                    </TD>
                                                    <TD>
                                                    <s:property value="#cust.cust_phone" />
                                                    </TD>
                                                    <TD>
                                                    <s:property value="#cust.cust_mobile" />
                                                    </TD>
                                                    <TD>
                                                    <a href="${pageContext.request.contextPath }/customerServlet?method=edit&custId=${customer.cust_id}">修改</a>
                                                    &nbsp;&nbsp;
                                                    <a href="${pageContext.request.contextPath }/customerServlet?method=delete&custId=${customer.cust_id}">刪除</a>
                                                    </TD>
                                                </TR>
                                                </s:iterator>

                                            </TBODY>
                                        </TABLE>
                                    </TD>
                                </TR>
                                
                                <TR>
                                    <TD><SPAN id=pagelink>
                                            <DIV
                                                style="LINE-HEIGHT: 20px; HEIGHT: 20px; TEXT-ALIGN: right">
                                                共[<B><s:property value="#pageBean.totalCount" /> </B>]條記錄,[<B><s:property value="#pageBean.totalPage" /></B>]頁
                                                ,每頁顯示 <%-- changePageSize($(‘#pageSizeSelect option‘).filter(‘:selected‘).val()) --%> 
                                                <select name="pageSize" onchange="changePageSize($(‘#pageSizeSelect option:selected‘).val())" id="pageSizeSelect" >
                                                    <option value="3" <s:property value="#pageBean.pageSize==3?‘selected‘:‘‘" /> >3</option>
                                                    <option value="5" <s:property value="#pageBean.pageSize==5?‘selected‘:‘‘" /> >5</option>
                                                </select>
                                                條
                                                [<A href="javaScript:void(0)" onclick="changePage(<s:property value=‘#pageBean.currentPage-1‘ />)" >前一頁</A>]
                                                <B><s:property value="#pageBean.currentPage" /></B>
                                                [<A href="javaScript:void(0)" onclick="changePage(<s:property value=‘#pageBean.currentPage+1‘ />)"  >後一頁</A>] 
                                                到
                                                <input type="text" size="3" id="page" name="page" value="<s:property value="#pageBean.currentPage" />"  />
                                                頁
                                                
                                                <input type="button" value="Go" onclick="changePage($(‘#page‘).val())"/>
                                            </DIV>
                                    </SPAN></TD>
                                </TR>
                            </TBODY>
                        </TABLE>
                    </TD>
                    <TD width=15 background="${pageContext.request.contextPath }/images/new_023.jpg"><IMG
                        src="${pageContext.request.contextPath }/images/new_023.jpg" border=0></TD>
                </TR>
            </TBODY>
        </TABLE>
        <TABLE cellSpacing=0 cellPadding=0 width="98%" border=0>
            <TBODY>
                <TR>
                    <TD width=15><IMG src="${pageContext.request.contextPath }/images/new_024.jpg"
                        border=0></TD>
                    <TD align=middle width="100%"
                        background="${pageContext.request.contextPath }/images/new_025.jpg" height=15></TD>
                    <TD width=15><IMG src="${pageContext.request.contextPath }/images/new_026.jpg"
                        border=0></TD>
                </TR>
            </TBODY>
        </TABLE>
    
</BODY>
</HTML>

二、BaseDao封裝

  1.抽取BaseDao

技術分享

  2.BaseDao設計思路

技術分享

  3.BaseDao接口書寫

public interface BaseDao<T> {
    //
    void save(T t);
    //
    void delete(T t);
    //
    void delete(Serializable id);
    //
    void update(T t);
    //查 根據id查詢
    T    getById(Serializable id);
    //查 符合條件的總記錄數
    Integer    getTotalCount(DetachedCriteria dc);
    //查 查詢分頁列表數據
    List<T> getPageList(DetachedCriteria dc,Integer start,Integer pageSize);
    
}

  4.BaseDao的實現類

public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

    private Class clazz;//用於接收運行期泛型類型
    
    
    public BaseDaoImpl() {
        //獲得當前類型的帶有泛型類型的父類
        ParameterizedType ptClass = (ParameterizedType) this.getClass().getGenericSuperclass();
        //獲得運行期的泛型類型
        clazz = (Class) ptClass.getActualTypeArguments()[0];
    }

    @Override
    public void save(T t) {
        getHibernateTemplate().save(t);
    }

    @Override
    public void delete(T t) {
        
        getHibernateTemplate().delete(t);
        
    }

    @Override
    public void delete(Serializable id) {
        T t = this.getById(id);//先取,再刪
        getHibernateTemplate().delete(t);
    }

    @Override
    public void update(T t) {
        getHibernateTemplate().update(t);
    }

    @Override
    public T getById(Serializable id) {
        
        
        
        return (T) getHibernateTemplate().get(clazz, id);
    }

    @Override
    public Integer getTotalCount(DetachedCriteria dc) {
        //設置查詢的聚合函數,總記錄數
        dc.setProjection(Projections.rowCount());
        
        List<Long> list = (List<Long>) getHibernateTemplate().findByCriteria(dc);
        
        //清空之前設置的聚合函數
        dc.setProjection(null);
        
        if(list!=null && list.size()>0){
            Long count = list.get(0);
            return count.intValue();
        }else{
            return null;
        }
        
    }

    @Override
    public List<T> getPageList(DetachedCriteria dc, Integer start, Integer pageSize) {
        
        List<T> list = (List<T>) getHibernateTemplate().findByCriteria(dc, start, pageSize);
        
        return list;
    }
}

  5.業務Dao中的應用

public class CustomerDaoImpl extends BaseDaoImpl<Customer> implements CustomerDao {
    
}

JAVAEE——SSH項目實戰02:客戶列表和BaseDao封裝