【SSH網上商城項目實戰10】商品類基本模塊的搭建

轉自:http://blog.csdn.net/eson_15/article/details/51354932   

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

1. 數據庫建表並映射Model

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

  1. /*=============================*/  
  2. /* Table: 商品表結構            */  
  3. /*=============================*/  
  4. create table product  
  5. (  
  6.    /* 商品編號,自動增長 */  
  7.    id                  int primary key not null auto_increment,  
  8.    /* 商品名稱 */  
  9.    name                varchar(20),  
  10.    /* 商品價格 */  
  11.    price               decimal(8,2),  
  12.    /* 商品圖片 */  
  13.    pic                 varchar(200),  
  14.    /* 商品簡單介紹 */  
  15.    remark              longtext,  
  16.    /* 商品詳細介紹 */  
  17.    xremark             longtext,  
  18.    /* 商品生產日期 */  
  19.    date                timestamp default CURRENT_TIMESTAMP,  
  20.    /* 是否爲推薦商品,推薦商品纔有可能顯示在商城首頁 */  
  21.    commend             bool,  
  22.    /* 是否爲有效商品,有效商品纔有可能顯示在商城首頁 */  
  23.    open                bool,  
  24.    /* 商品所在的類別編號*/  
  25.    cid                  int,  
  26.    constraint cid_FK foreign key(cid) references category(id)  
  27. );  
/*=============================*/
/* 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的架構出來,具體如下:

  1. //ProductService接口繼承BaseService<Product>  
  2. public interface ProductService extends BaseService<Product> {  
  3.       
  4. }  
  5.   
  6. //ProductServiceImpl實現類繼承BaseServiceImpl<Product>,並實現上面的ProductService接口  
  7. @Service("productService")  
  8. public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {  
  9.   
  10. }   
//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層的註解

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

	@Resource
	protected ProductService productService;

        //其他代碼省略,還是原來的代碼……	
}
        然後我們寫一個ProductAction繼承該方法:

  1. public class ProductAction extends BaseAction<Product> {  
  2.       
  3. }  
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的框架:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  3. <html>  
  4.   <head>  
  5.     <%@ include file="/public/head.jspf" %>  
  6.     <style type="text/css">  
  7.         body {  
  8.             margin: 1px;  
  9.         }  
  10.         .searchbox {  
  11.           margin: -3;  
  12.         }  
  13.     </style>  
  14.     <script type="text/javascript">  
  15.         $(function(){  
  16.             $('#dg').datagrid({     
  17.                 //url地址改爲請求productAction中的queryJoinCategory方法  
  18.                 url:'product_queryJoinCategory.action',  
  19.                 loadMsg:'Loading......',  
  20.                 queryParams:{name:''},//這裏參數改成name,參數值爲空,表示我們要顯示所有商品,後臺是根據商品name屬性查詢的  
  21.                 //width:300,  
  22.                 fitColumns:true,  
  23.                 striped:true,  
  24.                 nowrap:true,  
  25.                 singleSelect:false,  
  26.                 pagination:true,  
  27.                 pageSize:5,  
  28.                 pageList:[5,10,15,20],  
  29.                 idField:'id',//指定id爲標識字段,在刪除,更新的時候有用,如果配置此字段,在翻頁時,換頁不會影響選中的項  
  30.                   
  31.                 //toolbar定義添加、刪除、更新按鈕以及搜索框  
  32.                 toolbar: [{  
  33.                     iconCls: 'icon-add',  
  34.                     text:'添加商品',  
  35.                     handler: function(){  
  36.                         //添加觸發代碼  
  37.                     }  
  38.                  },'-',{  
  39.                     iconCls: 'icon-edit',  
  40.                     text:'更新商品',  
  41.                     handler: function(){  
  42.                                             //添加觸發代碼  
  43.                     }  
  44.                  },'-',{  
  45.                     iconCls: 'icon-remove',  
  46.                      text:'刪除商品',  
  47.                     handler: function(){  
  48.                         //添加觸發代碼                      
  49.                     }  
  50.                 },'-',{ //查詢按鈕不是LinkButton,它有語法,但是也支持解析HTML標籤  
  51.                     text:"<input id='ss' name='serach' />"  
  52.                 }],  
  53.                 rowStyler: function(index,row){  
  54.                     console.info("index" + index + "," + row)  
  55.                     if(index % 2 == 0) {  
  56.                         return 'background-color:#fff;';  
  57.                     } else {  
  58.                         return 'background-color:#c4e1e1;';  
  59.                     }  
  60.                       
  61.                  },  
  62.                 frozenColumns:[[  
  63.                      {field:'checkbox',checkbox:true},  
  64.                     {field:'id',title:'商品編號',width:100}     
  65.                  ]],  
  66.                 columns:[[                       
  67.                     {field:'name',title:'商品名稱',width:100},      
  68.                     {field:'price',title:'商品價格',width:100},  
  69.                     {field:'remark',title:'簡單描述',width:100},  
  70.                     {field:'xremark',title:'詳細描述',width:100},  
  71.                     {field:'date',title:'上架時間',width:100},  
  72.                     {field:'commend',title:'推薦商品',width:100,    
  73.                         formatter: function(value,row,index){  
  74.                             if(value) {  
  75.                                 return "<input type='checkbox' checked='checked' disabled='true'";  
  76.                             } else {  
  77.                                 return "<input type='checkbox' disabled='true'";  
  78.                             }  
  79.                          }  
  80.                     },  
  81.                     {field:'open',title:'有效商品',width:100,    
  82.                         formatter: function(value,row,index){  
  83.                             if(value) {  
  84.                                 return "<input type='checkbox' checked='checked' disabled='true'";  
  85.                             } else {  
  86.                                 return "<input type='checkbox' disabled='true'";  
  87.                             }  
  88.                         }  
  89.                      },  
  90.                     {field:'category.type',title:'所屬商品類別',width:200, //category.type是商品類別  
  91.                         formatter: function(value,row,index){  
  92.                             if(row.category != null && row.category.type != null) {  
  93.                                 return row.category.type; //如果商品類別不爲空,返回商品類別  
  94.                             } else {  
  95.                                 return "此商品暫時未分類";  
  96.                             }  
  97.                          }    
  98.                     }  
  99.                 ]]      
  100.             });   
  101.             //把普通的文本框轉化爲查詢搜索文本框  
  102.             $('#ss').searchbox({   
  103.                 //觸發查詢事件  
  104.                  searcher:function(value,name){ //value表示輸入的值  
  105.                     //添加觸發代碼  
  106.                 },   
  107.                 prompt:'請輸入搜索關鍵字'   
  108.             });   
  109.         });  
  110.     </script>  
  111.   </head>  
  112.     
  113.   <body>  
  114.     <table id="dg"></table>  
  115.       
  116.   </body>  
  117. </html>  
<%@ 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部分,我們都是先從底層慢慢往上開發的:

  1. //ProductService接口  
  2. public interface ProductService extends BaseService<Product> {  
  3.       
  4.     //查詢商品信息,級聯類別  
  5.     public List<Product> queryJoinCategory(String type, int page, int size); //使用商品的名稱查詢  
  6.     //根據關鍵字查詢總記錄數  
  7.     public Long getCount(String type);  
  8. }  
  9.   
  10. @SuppressWarnings("unchecked")  
  11. @Service("productService")  
  12. public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {  
  13.   
  14.     @Override  
  15.     public List<Product> queryJoinCategory(String name, int page, int size) {  
  16.         String hql = "from Product p left join fetch p.category where p.name like :name";  
  17.         return getSession().createQuery(hql)  
  18.                 .setString("name""%" + name + "%")  
  19.                 .setFirstResult((page-1) * size) //從第幾個開始顯示  
  20.                 .setMaxResults(size) //顯示幾個  
  21.                 .list();  
  22.     }  
  23.       
  24.     @Override  
  25.     public Long getCount(String name) {  
  26.         String hql = "select count(p) from Product p where p.name like :name";  
  27.         return (Long) getSession().createQuery(hql)  
  28.             .setString("name""%" + name + "%")  
  29.             .uniqueResult(); //返回一條記錄:總記錄數  
  30.     }  
  31.   
  32. }  
//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方法了:

  1. @Controller("productAction")  
  2. @Scope("prototype")  
  3. public class ProductAction extends BaseAction<Product> {  
  4.       
  5.     public String queryJoinCategory() {  
  6.         System.out.println("name:" + model.getName());  
  7.         System.out.println("page:" + page);  
  8.         System.out.println("rows:" + rows);  
  9.           
  10.         //用來存儲分頁的數據  
  11.         pageMap = new HashMap<String, Object>();  
  12.           
  13.         //根據關鍵字和分頁的參數查詢相應的數據  
  14.         List<Product> productList = productService.queryJoinCategory(model.getName(), page, rows);  
  15.         pageMap.put("rows", productList); //存儲爲JSON格式  
  16.         //根據關鍵字查詢總記錄數  
  17.         Long total = productService.getCount(model.getName());  
  18. //      System.out.println(total);  
  19.         pageMap.put("total", total); //存儲爲JSON格式  
  20.         return "jsonMap";  
  21.     }  
  22.   
  23. }  
@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中進行配置,跟之前的商品類一樣的流程,到這裏可以看出,開發好了一個,下面一個就快了:

  1. <action name="product_*" class="productAction" method="{1}">  
  2.     <result name="jsonMap" type="json">  
  3.         <param name="root">pageMap</param>  
  4.         <param name="excludeProperties">  
  5.             <!-- rows[0].category.account -->  
  6.             <!-- 把所有account過濾掉,否則會出現懶加載問題,該部分下面截圖 -->           
  7.         </param>  
  8.     </result>  
  9. </action>  
<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,測試一下,當我們點擊左側菜單欄的商品管理時,會彈出右邊如下窗口:

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



        相關閱讀:http://blog.csdn.net/column/details/str2hiberspring.html

        整個項目的源碼下載地址:http://blog.csdn.net/eson_15/article/details/51479994

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章