文章出處

    前面我們完成了與商品類別相關的業務邏輯,接下來我們開始做具體商品部分。

1. 數據庫建表并映射Model

        首先我們在數據庫中新建一張表,然后使用逆向工程將表映射成Model類,表如下:

/*=============================*/  
/* Table: 商品表結構            */  
/*=============================*/  
create table product  
(  
   /* 商品編號,自動增長 */  
   id                  int primary key not null auto_increment,  
   /* 商品名稱 */  
   name                varchar(20),  
   /* 商品價格 */  
   price               decimal(8,2),  
   /* 商品圖片 */  
   pic                 varchar(200),  
   /* 商品簡單介紹 */  
   remark              longtext,  
   /* 商品詳細介紹 */  
   xremark             longtext,  
   /* 商品生產日期 */  
   date                timestamp default CURRENT_TIMESTAMP,  
   /* 是否為推薦商品,推薦商品才有可能顯示在商城首頁 */  
   commend             bool,  
   /* 是否為有效商品,有效商品才有可能顯示在商城首頁 */  
   open                bool,  
   /* 商品所在的類別編號*/  
   cid                  int,  
   constraint cid_FK foreign key(cid) references category(id)  
);

   使用逆向工程映射為Model類就不贅述了,前面有提到如何使用逆向工程生成Model。

 

2. 完成商品類的Service層和Action的架構

2.1 商品類的Service層架構

與前面category一樣,product也得有個service來操作與商品相關的業務邏輯,所以我們得寫一個ProductService和ProductServiceImpl的架構出來,具體如下:

//ProductService接口繼承BaseService<Product>  
public interface ProductService extends BaseService<Product> {  
      
}  
  
//ProductServiceImpl實現類繼承BaseServiceImpl<Product>,并實現上面的ProductService接口  
@Service("productService")  
public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {  
  
} 

2.2 商品類的Action架構

        首先得完善一下BaseAction中關于Service層的注解

@Controller("baseAction")  
@Scope("prototype")  
public class BaseAction<T> extends ActionSupport implements RequestAware,SessionAware,ApplicationAware,ModelDriven<T> {  
  
    @Resource  
    protected ProductService productService;  
  
        //其他代碼省略,還是原來的代碼……    
} 

   然后我們寫一個ProductAction繼承該方法:

public class ProductAction extends BaseAction<Product> {  
      
} 

    至此,關于商品的后臺架構就基本搭建好了,接下來就是完善里面的具體功能和業務邏輯了。

3. 完成前臺的基本結構

        前臺的基本結構和商品類的一樣,我們看一下已經完成的商品類的前臺都有哪些文件:

        我們先根據其商品類的前臺文件,拷貝一份到product文件夾中,然后我們再做相應的修改。先來分析一下流程:首先index.jsp到aindex.jsp顯示左側菜單欄,當點擊類別管理時,進入category/query.jsp頁面右側顯示所有商品類別信息,搜索和刪除功能均在此頁面,不需要彈出新的窗口,添加彈出save.jsp窗口,更新彈出update.jsp窗口。當點擊商品管理的時候,進入product/query.jsp頁面右側顯示所有商品信息,搜索和刪除功能均在此頁面完成,添加和更新分別彈出save.jsp和update.jsp。接下來我們把各個頁面的框架搭建好,然后往相應的部分填東西即可。

        首先在aindex.jsp中添加如下代碼:

       接下來,我們完成query.jsp的框架:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <%@ include file="/public/head.jspf" %>  
    <style type="text/css">  
        body {  
            margin: 1px;  
        }  
        .searchbox {  
          margin: -3;  
        }  
    </style>  
    <script type="text/javascript">  
        $(function(){  
            $('#dg').datagrid({     
                //url地址改為請求productAction中的queryJoinCategory方法  
                url:'product_queryJoinCategory.action',  
                loadMsg:'Loading......',  
                queryParams:{name:''},//這里參數改成name,參數值為空,表示我們要顯示所有商品,后臺是根據商品name屬性查詢的  
                //width:300,  
                fitColumns:true,  
                striped:true,  
                nowrap:true,  
                singleSelect:false,  
                pagination:true,  
                pageSize:5,  
                pageList:[5,10,15,20],  
                idField:'id',//指定id為標識字段,在刪除,更新的時候有用,如果配置此字段,在翻頁時,換頁不會影響選中的項  
                  
                //toolbar定義添加、刪除、更新按鈕以及搜索框  
                toolbar: [{  
                    iconCls: 'icon-add',  
                    text:'添加商品',  
                    handler: function(){  
                        //添加觸發代碼  
                    }  
                 },'-',{  
                    iconCls: 'icon-edit',  
                    text:'更新商品',  
                    handler: function(){  
                                            //添加觸發代碼  
                    }  
                 },'-',{  
                    iconCls: 'icon-remove',  
                     text:'刪除商品',  
                    handler: function(){  
                        //添加觸發代碼                      
                    }  
                },'-',{ //查詢按鈕不是LinkButton,它有語法,但是也支持解析HTML標簽  
                    text:"<input id='ss' name='serach' />"  
                }],  
                rowStyler: function(index,row){  
                    console.info("index" + index + "," + row)  
                    if(index % 2 == 0) {  
                        return 'background-color:#fff;';  
                    } else {  
                        return 'background-color:#c4e1e1;';  
                    }  
                      
                 },  
                frozenColumns:[[  
                     {field:'checkbox',checkbox:true},  
                    {field:'id',title:'商品編號',width:100}     
                 ]],  
                columns:[[                       
                    {field:'name',title:'商品名稱',width:100},      
                    {field:'price',title:'商品價格',width:100},  
                    {field:'remark',title:'簡單描述',width:100},  
                    {field:'xremark',title:'詳細描述',width:100},  
                    {field:'date',title:'上架時間',width:100},  
                    {field:'commend',title:'推薦商品',width:100,    
                        formatter: function(value,row,index){  
                            if(value) {  
                                return "<input type='checkbox' checked='checked' disabled='true'";  
                            } else {  
                                return "<input type='checkbox' disabled='true'";  
                            }  
                         }  
                    },  
                    {field:'open',title:'有效商品',width:100,    
                        formatter: function(value,row,index){  
                            if(value) {  
                                return "<input type='checkbox' checked='checked' disabled='true'";  
                            } else {  
                                return "<input type='checkbox' disabled='true'";  
                            }  
                        }  
                     },  
                    {field:'category.type',title:'所屬商品類別',width:200, //category.type是商品類別  
                        formatter: function(value,row,index){  
                            if(row.category != null && row.category.type != null) {  
                                return row.category.type; //如果商品類別不為空,返回商品類別  
                            } else {  
                                return "此商品暫時未分類";  
                            }  
                         }    
                    }  
                ]]      
            });   
            //把普通的文本框轉化為查詢搜索文本框  
            $('#ss').searchbox({   
                //觸發查詢事件  
                 searcher:function(value,name){ //value表示輸入的值  
                    //添加觸發代碼  
                },   
                prompt:'請輸入搜索關鍵字'   
            });   
        });  
    </script>  
  </head>  
    
  <body>  
    <table id="dg"></table>  
      
  </body>  
</html>  

 接下來我們完成productAction中的queryJoinCategory方法,在這之前,先要完成service部分,我們都是先從底層慢慢往上開發的:

//ProductService接口  
public interface ProductService extends BaseService<Product> {  
      
    //查詢商品信息,級聯類別  
    public List<Product> queryJoinCategory(String type, int page, int size); //使用商品的名稱查詢  
    //根據關鍵字查詢總記錄數  
    public Long getCount(String type);  
}  
  
@SuppressWarnings("unchecked")  
@Service("productService")  
public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {  
  
    @Override  
    public List<Product> queryJoinCategory(String name, int page, int size) {  
        String hql = "from Product p left join fetch p.category where p.name like :name";  
        return getSession().createQuery(hql)  
                .setString("name", "%" + name + "%")  
                .setFirstResult((page-1) * size) //從第幾個開始顯示  
                .setMaxResults(size) //顯示幾個  
                .list();  
    }  
      
    @Override  
    public Long getCount(String name) {  
        String hql = "select count(p) from Product p where p.name like :name";  
        return (Long) getSession().createQuery(hql)  
            .setString("name", "%" + name + "%")  
            .uniqueResult(); //返回一條記錄:總記錄數  
    }  
  
}  

 下面可以完成productAction中的queryJoinCategory方法了:

@Controller("productAction")  
@Scope("prototype")  
public class ProductAction extends BaseAction<Product> {  
      
    public String queryJoinCategory() {  
        System.out.println("name:" + model.getName());  
        System.out.println("page:" + page);  
        System.out.println("rows:" + rows);  
          
        //用來存儲分頁的數據  
        pageMap = new HashMap<String, Object>();  
          
        //根據關鍵字和分頁的參數查詢相應的數據  
        List<Product> productList = productService.queryJoinCategory(model.getName(), page, rows);  
        pageMap.put("rows", productList); //存儲為JSON格式  
        //根據關鍵字查詢總記錄數  
        Long total = productService.getCount(model.getName());  
//      System.out.println(total);  
        pageMap.put("total", total); //存儲為JSON格式  
        return "jsonMap";  
    }  
  
} 

    接下來在struts.xml中進行配置,跟之前的商品類一樣的流程,到這里可以看出,開發好了一個,下面一個就快了:

<action name="product_*" class="productAction" method="{1}">  
    <result name="jsonMap" type="json">  
        <param name="root">pageMap</param>  
        <param name="excludeProperties">  
            <!-- rows[0].category.account -->  
            <!-- 把所有account過濾掉,否則會出現懶加載問題,該部分下面截圖 -->           
        </param>  
    </result>  
</action>  


       這樣后臺程序寫好了,然后開啟tomcat,測試一下,當我們點擊左側菜單欄的商品管理時,會彈出右邊如下窗口:

        這樣我們就完成了商品管理窗口的框架了。

 

  

本篇可能遇到的問題是 點擊2個導航欄 顯示同一個表的數據 檢查了query.jsp URL完全不同的2個地址

為何會出現這樣 debug 也不觸發 原因就是aindex.jsp里面

創建tab時候 寫的是// content:'<iframe src="send_category_query.action" frameborder="0" width="100%" height="100%"/>'需要改為

content:'<iframe title=' + text + ' src=' + href + ' frameborder="0" width="100%" height="100%"/>'


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()