ssm項目練習-電商平臺後臺管理系統_2

聲明還是寫在前面,這裏的代碼都是直接複製過來的,再我第二遍寫這個項目的時候會把每個功能模塊的代碼細細拆分,說明每一步的步驟。

7.後臺登陸與管理首頁面

引入EasyUi所需文件
在這裏插入圖片描述
登陸界面admin_login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>電子商務平臺——後臺登錄頁</title>
<!-- 引入EasyUI的相關css和js文件 -->
<link href="EasyUI/themes/default/easyui.css" rel="stylesheet"
	type="text/css" />
<link href="EasyUI/themes/icon.css" rel="stylesheet" type="text/css" />
<link href="EasyUI/demo.css" rel="stylesheet" type="text/css" />
<script src="EasyUI/jquery.min.js" type="text/javascript"></script>
<script src="EasyUI/jquery.easyui.min.js" type="text/javascript"></script>
<script src="EasyUI/easyui-lang-zh_CN.js" type="text/javascript"></script>
</head>

<body>
	<script type="text/javascript">
		function clearForm() {
			$('#adminLoginForm').form('clear');
		}

      function checkAdminLogin() {
			$("#adminLoginForm").form("submit", {
				// 向控制器類AdminInfoController中login方法發送請求
				url : 'admininfo/login', 
				success : function(result) {
					var result = eval('(' + result + ')');
					if (result.success == 'true') {
						window.location.href = 'admin.jsp';
						$("#adminLoginDlg").dialog("close");
					} else {
						$.messager.show({
							title : "提示信息",
							msg : result.message
						});
					}
				}
			});
		}
	</script>
	<div id="adminLoginDlg" class="easyui-dialog"
		style="left: 550px; top: 200px;width: 300;height: 200"
		data-options="title:'後臺登錄',buttons:'#bb',modal:true">
		<form id="adminLoginForm" method="post">
			<table style="margin:20px;font-size: 13;">
				<tr>
					<th >用戶名</th>
					<td><input class="easyui-textbox" type="text" id="name"
						name="name" data-options="required:true" value="admin"></input></td>
				</tr>
				<tr>
					<th>密碼</th>
					<td><input class="easyui-textbox" type="text" id="pwd"
						name="pwd" data-options="required:true" value="123456"></input></td>
				</tr>
			</table>
		</form>
	</div>
	<div id="bb">
		<a href="javascript:void(0)" class="easyui-linkbutton"
			onclick="checkAdminLogin()">登錄</a> <a href="javascript:void(0)"
			class="easyui-linkbutton" onclick="clearForm();">重置</a>
	</div>

</body>
</html>

裏面用到的控制器類AdminInfoController ,這會只寫了login,一會還有其他功能,後續會添加。

@SessionAttributes(value = { "admin" })
@Controller
@RequestMapping("/admininfo")
public class AdminInfoController {
	@Autowired
	private AdminInfoService adminInfoService;

	@RequestMapping(value = "/login", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String login(AdminInfo ai, ModelMap model) {
		// 後臺登錄驗證
		AdminInfo admininfo = adminInfoService.login(ai);
		if (admininfo != null && admininfo.getName() != null) {
			// 驗證通過後,再判斷是否已爲該管理員分配功能權限
			if (adminInfoService.getAdminInfoAndFunctions(admininfo.getId()).getFs().size() > 0) {
				// 驗證通過且已分配功能權限,則將admininfo對象存入model中
				model.put("admin", admininfo);
				// 以JSON格式向頁面發送成功信息
				return "{\"success\":\"true\",\"message\":\"登錄成功\"}";
			} else {
				return "{\"success\":\"false\",\"message\":\"您沒有權限,請聯繫超級管理員設置權限!\"}";
			}
		} else
			return "{\"success\":\"false\",\"message\":\"登錄失敗\"}";
	}

登陸成功後進入後臺管理首頁admin.jsp
先大概給個預覽圖,方便對比觀察代碼
在這裏插入圖片描述

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%
	if (session.getAttribute("admin") == null)
		response.sendRedirect("/ecpbm/admin_login.jsp");
%>

<html>
<head>

<title>後臺管理首頁面</title>

<link href="EasyUI/themes/default/easyui.css" rel="stylesheet"
	type="text/css" />
<link href="EasyUI/themes/icon.css" rel="stylesheet" type="text/css" />
<link href="EasyUI/demo.css" rel="stylesheet" type="text/css" />
<script src="EasyUI/jquery.min.js" type="text/javascript"></script>
<script src="EasyUI/jquery.easyui.min.js" type="text/javascript"></script>
<script src="EasyUI/easyui-lang-zh_CN.js" type="text/javascript"></script>
</head>

<body class="easyui-layout">
	<div data-options="region:'north',border:false"
		style="height: 60px; background: #B3DFDA; padding: 10px">
		<div align="left">
			<div style="font-family: Microsoft YaHei; font-size: 16px;">電商平臺後臺管理系統</div>
		</div>
		<div align="right">
			歡迎您,<font color="Red">${sessionScope.admin.name}</font>
		</div>
	</div>
	<div data-options="region:'west',split:true,title:'功能菜單'"
		style="width: 180px">
		<ul id="tt"></ul>
	</div>
	<div data-options="region:'south',border:false"
		style="height: 50px; background: #A9FACD; padding: 10px; text-align: center">powered
		by fzj</div>
	<div data-options="region:'center'">
		<div id="tabs" data-options="fit:true" class="easyui-tabs"
			style="width: 500px; height: 250px;"></div>
	</div>
	<script type="text/javascript">
		// 爲tree指定數據
		$('#tt').tree({
			url : 'admininfo/getTree?adminid=${sessionScope.admin.id}'
		});
		$('#tt').tree({
			onClick : function(node) {
				if ("商品列表" == node.text) {
					if ($('#tabs').tabs('exists', '商品列表')) {
						$('#tabs').tabs('select', '商品列表');
					} else {
						$('#tabs').tabs('add', {
							title : node.text,
							href : 'productlist.jsp',
							closable : true
						});
					}
				} else if ("商品類型列表" == node.text) {
					if ($('#tabs').tabs('exists', '商品類型列表')) {
						$('#tabs').tabs('select', '商品類型列表');
					} else {
						$('#tabs').tabs('add', {
							title : node.text,
							href : 'typelist.jsp',
							closable : true
						});
					}
				} else if ("查詢訂單" == node.text) {
					if ($('#tabs').tabs('exists', '查詢訂單')) {
						$('#tabs').tabs('select', '查詢訂單');
					} else {
						$('#tabs').tabs('add', {
							title : node.text,
							href : 'searchorder.jsp',
							closable : true
						});
					}
				} else if ("創建訂單" == node.text) {
					if ($('#tabs').tabs('exists', '創建訂單')) {
						$('#tabs').tabs('select', '創建訂單');
					} else {
						$('#tabs').tabs('add', {
							title : node.text,
							href : 'createorder.jsp',
							closable : true
						});
					}
				} else if ("客戶列表" == node.text) {
					if ($('#tabs').tabs('exists', '客戶列表')) {
						$('#tabs').tabs('select', '客戶列表');
					} else {
						$('#tabs').tabs('add', {
							title : node.text,
							href : 'userlist.jsp',
							closable : true
						});
					}
				} else if ("退出系統" == node.text) {
					$.ajax({
						url : 'admininfo/logout',
						success : function(data) {
							window.location.href = "admin_login.jsp";
						}
					})
				}
			}
		});
	</script>
</body>
</html>

可以看到左側有一個樹控件,所以我們要把functions轉換成json格式展示到前端
退出登錄的功能順便也寫這了。

//進行json格式轉換,併發送到前端頁面
@RequestMapping("getTree")
@ResponseBody
public List<TreeNode> getTree(@RequestParam(value = "adminid") String adminid) {
	// 根據管理員編號,獲取AdminInfo對象
	AdminInfo admininfo = adminInfoService.getAdminInfoAndFunctions(Integer.parseInt(adminid));
	List<TreeNode> nodes = new ArrayList<TreeNode>();
	// 獲取關聯的Functions對象集合
	List<Functions> functionsList = admininfo.getFs();
	// 對List<Functions>類型的Functions對象集合排序
	Collections.sort(functionsList);
	// 將排序後的Functions對象集合轉換到List<TreeNode>類型的列表nodes
	for (Functions functions : functionsList) {
		TreeNode treeNode = new TreeNode();
		treeNode.setId(functions.getId());
		treeNode.setFid(functions.getParentid());
		treeNode.setText(functions.getName());
		nodes.add(treeNode);
	}
	// 調用自定義的工具類JsonFactory的buildtree方法,爲nodes列表中的各個TreeNode元素中的
	// children屬性賦值(該節點包含的子節點)
	List<TreeNode> treeNodes = JsonFactory.buildtree(nodes, 0);
	return treeNodes;
}

	// 退出
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	@ResponseBody
	public String logout(SessionStatus status) {
		// @SessionAttributes清除
		status.setComplete();
		return "{\"success\":\"true\",\"message\":\"註銷成功\"}";
	}

實現代碼中提到的JsonFactory

package com.ecpbm.util;

import java.util.ArrayList;
import java.util.List;

import com.ecpbm.pojo.TreeNode;


public class JsonFactory {
	public static List<TreeNode> buildtree(List<TreeNode> nodes, int id) {
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		for (TreeNode treeNode : nodes) {
			TreeNode node = new TreeNode();
			node.setId(treeNode.getId());
			node.setText(treeNode.getText());
			if (id == treeNode.getFid()) {
				// 遞給調用buildtree方法給TreeNode中的children屬性賦值
				node.setChildren(buildtree(nodes, node.getId()));
				treeNodes.add(node);
			}
		}
		return treeNodes;
	}
}

此時可以運行測試一下,結果圖片我放在上面了。

8.商品管理

商品列表頁productlist.jsp

<%@ page language="java" import="java.util.*"
	contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>商品列表頁</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
	<!-- 定義table, 用於創建easy ui的datagrid控件 -->
	<table id="dg_productinfo" class="easyui-datagrid"></table>
	<!-- 創建datagrid控件的工具欄 -->
	<div id="tb_productinfo" style="padding: 2px 5px;">
		<a href="javascript:void(0)" class="easyui-linkbutton"
			iconCls="icon-add" plain="true" onclick="addProduct();">添加</a> <a
			href="javascript:void(0)" class="easyui-linkbutton"
			iconCls="icon-edit" plain="true" onclick="editProduct();">修改</a> <a
			href="javascript:void(0)" class="easyui-linkbutton"
			iconCls="icon-remove" onclick="removeProduct();" plain="true">刪除</a>
	</div>

	<!-- 創建查詢工具欄 -->
	<div id="searchtb_productinfo" style="padding: 2px 5px;">
		<form id="searchForm_productinfo" method="post">
			<div style="padding: 3px">
				商品編號&nbsp;&nbsp;<input class="easyui-textbox"
					name="productinfo_search_code" id="productinfo_search_code"
					style="width: 110px" />
			</div>
			<div style="padding: 3px">
				商品名稱&nbsp;&nbsp;<input class="easyui-textbox"
					name="productinfo_search_name" id="productinfo_search_name"
					style="width: 110px" /> &nbsp;&nbsp;商品類型&nbsp;&nbsp;<input
					style="width: 110px;" id="productinfo_search_tid"
					class="easyui-combobox" name="productinfo_search_tid"
					data-options="valueField:'id',textField:'name',url:'type/getType/1'"
					value="0">&nbsp;&nbsp; 商品品牌&nbsp;&nbsp;<input
					class="easyui-textbox" name="productinfo_search_brand"
					id="productinfo_search_brand" style="width: 110px" />
				&nbsp;&nbsp;價格: <input class="easyui-numberbox"
					name="productinfo_search_priceFrom"
					id="productinfo_search_priceFrom" style="width: 80px;" /> ~ <input
					class="easyui-numberbox" name="productinfo_search_priceTo"
					id="productinfo_search_priceTo" style="width: 80px;" />
				&nbsp;&nbsp;<a href="javascript:void(0)" class="easyui-linkbutton"
					iconCls="icon-search" plain="true" onclick="searchProduct();">查找</a>
			</div>
		</form>
	</div>

	<!-- 添加商品信息對話框 -->
	<div id="dlg_productinfo" class="easyui-dialog" title="添加商品"
		closed="true" style="width: 500px;">
		<div style="padding: 10px 60px 20px 60px">
			<form id="ff_productinfo" method="POST" action=""
				enctype="multipart/form-data">
				<table cellpadding="5">
					<tr>
						<td>商品狀態:</td>
						<td><select id="status" class="easyui-combobox" name="status"
							style="width: 150px;">
								<option value="1">在售</option>
								<option value="0">下架</option>
						</select></td>
					</tr>
					<tr>
						<td>商品類型:</td>
						<td><input style="width: 150px;" id="type.id"
							class="easyui-combobox" name="type.id"
							data-options="valueField:'id',textField:'name',url:'type/getType/0'"></input>
						</td>
					</tr>
					<tr>
						<td>商品名稱:</td>
						<td><input class="easyui-textbox" type="text" id="name"
							name="name" data-options="required:true"></input></td>
					</tr>
					<tr>
						<td>商品編碼:</td>
						<td><input class="easyui-textbox" type="text" id="code"
							name="code" data-options="required:true"></input></td>
					</tr>
					<tr>
						<td>商品品牌:</td>
						<td><input class="easyui-textbox" type="text" id="brand"
							name="brand" data-options="required:true"></input></td>
					</tr>
					<tr>
						<td>商品數量:</td>
						<td><input class="easyui-textbox" type="text" id="num"
							name="num" data-options="required:true"></input></td>
					</tr>
					<tr>
						<td>商品價格:</td>
						<td><input class="easyui-textbox" type="text" id="price"
							name="price" data-options="required:true"></input></td>
					</tr>
					<tr>
						<td>商品描述:</td>
						<td><input class="easyui-textbox" name="intro" id="intro"
							data-options="multiline:true" style="height: 60px"></input></td>
					</tr>
					<tr>
						<td>商品圖片:</td>
						<td><input class="easyui-filebox" id="file" name="file"
							style="width: 200px" value="選擇圖片"></input></td>
					</tr>
				</table>
			</form>
			<div style="text-align: center; padding: 5px">
				<a href="javascript:void(0)" class="easyui-linkbutton"
					onclick="saveProduct();">保存</a> <a href="javascript:void(0)"
					class="easyui-linkbutton" onclick="clearForm();">清空</a>
			</div>
		</div>
	</div>

	<script type="text/javascript">
		$(function() {
			$('#dg_productinfo').datagrid({
				singleSelect : false, //設置datagrid爲支持多選
				url : 'productinfo/list', //爲datagrid設置數據源
				pagination : true, //啓用分頁
				pageSize : 10, //設置初始每頁記錄數(頁大小)
				pageList : [ 10, 15, 20 ], //設置可供選擇的頁大小
				rownumbers : true, //顯示行號
				fit : true, //設置自適應
				toolbar : '#tb_productinfo', //爲datagrid添加工具欄
				header : '#searchtb_productinfo', //爲datagrid標頭添加搜索欄
				columns : [ [ { //編輯datagrid的列
					title : '序號',
					field : 'id',
					align : 'center',
					checkbox : true
				}, {
					field : 'name',
					title : '商品名稱',
					width : 200
				}, {
					field : 'type',
					title : '商品類型',
					formatter : function(value, row, index) {
						if (row.type) {
							return row.type.name;
						} else {
							return value;
						}
					},
					width : 60
				}, {
					field : 'status',
					title : '商品狀態',
					formatter : function(value, row, index) {
						if (row.status == 1) {
							return "在售";
						} else {
							return "下架";
						}
					},
					width : 60
				}, {
					field : 'code',
					title : '商品編碼',
					width : 100
				}, {
					field : 'brand',
					title : '品牌',
					width : 120
				}, {
					field : 'price',
					title : '價格',
					width : 50
				}, {
					field : 'num',
					title : '庫存',
					width : 50
				}, {
					field : 'intro',
					title : '商品描述',
					width : 450
				} ] ]
			});
		});

		var urls;
		var data;

		// 刪除商品(商品下架)
		function removeProduct() {
			var rows = $("#dg_productinfo").datagrid('getSelections');
			if (rows.length > 0) {
				$.messager.confirm('Confirm', '確認要刪除麼?', function(r) {
					if (r) {
						var ids = "";
						for (var i = 0; i < rows.length; i++) {
							ids += rows[i].id + ",";
						}
						$.post('productinfo/deleteProduct', {
							id : ids,
							flag : 0
						}, function(result) {
							if (result.success == 'true') {
								$("#dg_productinfo").datagrid('reload');
								$.messager.show({
									title : '提示信息',
									msg : result.message
								});
							} else {
								$.messager.show({
									title : '提示信息',
									msg : result.message
								});
							}
						}, 'json');
					}
				});
			} else {
				$.messager.alert('提示', '請選擇要刪除的行', 'info');
			}
		}

		// 打開新增商品對話框
		function addProduct() {
			$('#dlg_productinfo').dialog('open').dialog('setTitle', '新增商品');
			$('#dlg_productinfo').form('clear');
			urls = 'productinfo/addProduct';
		}

		// 保存商品信息
		function saveProduct() {
			$("#ff_productinfo").form("submit", {
				url : urls, //使用參數				
				success : function(result) {
					var result = eval('(' + result + ')');
					if (result.success == 'true') {
						$("#dg_productinfo").datagrid("reload");
						$("#dlg_productinfo").dialog("close");
					}
					$.messager.show({
						title : "提示信息",
						msg : result.message
					});
				}
			});
		}

		function clearForm() {
			$('#ff_productinfo').form('clear');
		}

		// 打開修改商品對話框(與新增商品對話框共用)
		function editProduct() {
			var rows = $("#dg_productinfo").datagrid('getSelections');
			if (rows.length > 0) {
				var row = $("#dg_productinfo").datagrid("getSelected");
				if (row) {
					$("#dlg_productinfo").dialog("open").dialog('setTitle',
							'修改商品信息');
					$("#ff_productinfo").form("load", {
						"type.id" : row.type.id,
						"name" : row.name,
						"code" : row.code,
						"brand" : row.brand,
						"num" : row.num,
						"price" : row.price,
						"intro" : row.intro,
						"status" : row.status,
					});
					urls = "productinfo/updateProduct?id=" + row.id;
				}
			} else {
				$.messager.alert('提示', '請選擇要修改的行', 'info');
			}
		}

		// 查詢商品
		function searchProduct() {
			var productinfo_search_code = $('#productinfo_search_code')
					.textbox("getValue");
			var productinfo_search_name = $('#productinfo_search_name')
					.textbox("getValue");
			var productinfo_search_tid = $('#productinfo_search_tid').combobox(
					"getValue");
			var productinfo_search_brand = $('#productinfo_search_brand')
					.textbox("getValue");
			var productinfo_search_priceFrom;
			if ($("#productinfo_search_priceFrom").val() != null
					&& $("#productinfo_search_priceFrom").val() != "") {
				productinfo_search_priceFrom = $(
						'#productinfo_search_priceFrom').textbox("getValue");
			} else {
				productinfo_search_priceFrom = "0";
			}
			var productinfo_search_priceTo;
			if ($("#productinfo_search_priceTo").val() != null
					&& $("#productinfo_search_priceTo").val() != "") {
				productinfo_search_priceTo = $('#productinfo_search_priceTo')
						.textbox("getValue");
			} else {
				productinfo_search_priceTo = "0";
			}
			$("#dg_productinfo").datagrid('load', {
				"code" : productinfo_search_code,
				"name" : productinfo_search_name,
				"type.id" : productinfo_search_tid,
				"brand" : productinfo_search_brand,
				"priceFrom" : productinfo_search_priceFrom,
				"priceTo" : productinfo_search_priceTo
			});
		}
	</script>
</body>
</html>

對應控制器ProductInfoController

package com.ecpbm.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ecpbm.pojo.Pager;
import com.ecpbm.pojo.ProductInfo;
import com.ecpbm.service.ProductInfoService;

@Controller
@RequestMapping("/productinfo")
public class ProductInfoController {
	@Autowired
	ProductInfoService productInfoService;

	// 後臺商品列表分頁顯示
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(Integer page, Integer rows, ProductInfo productInfo) {
		// 初始化分頁類對象pager
		Pager pager = new Pager();
		pager.setCurPage(page);
		pager.setPerPageRows(rows);
		// 創建params對象,封裝查詢條件
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("productInfo", productInfo);
		// 獲取滿足條件的商品總數
		int totalCount = productInfoService.count(params);
		// 獲取滿足條件的商品列表
		List<ProductInfo> productinfos = productInfoService.findProductInfo(productInfo, pager);
		// 創建result對象,保存查詢結果數據
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("total", totalCount);
		result.put("rows", productinfos);
		// 將結果以JSON格式發送到前端控制器
		return result;
	}

	// 添加商品
	@RequestMapping(value = "/addProduct", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String addProduct(ProductInfo pi, @RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		// 服務器端upload文件夾物理路徑
		String path = request.getSession().getServletContext().getRealPath("product_images");
		// 獲取文件名
		String fileName = file.getOriginalFilename();
		// 實例化一個File對象,表示目標文件(含物理路徑)
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			// 將上傳文件寫到服務器上指定的文件
			file.transferTo(targetFile);
			pi.setPic(fileName);
			productInfoService.addProductInfo(pi);
			return "{\"success\":\"true\",\"message\":\"商品添加成功\"}";
		} catch (Exception e) {
			return "{\"success\":\"false\",\"message\":\"商品添加失敗\"}";
		}
	}

	// 修改商品
	@RequestMapping(value = "/updateProduct", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String updateProduct(ProductInfo pi, @RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model) {
		// 服務器端upload文件夾物理路徑
		String path = request.getSession().getServletContext().getRealPath("product_images");
		// 獲取文件名
		String fileName = file.getOriginalFilename();
		// 實例化一個File對象,表示目標文件(含物理路徑)
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			// 將上傳文件寫到服務器上指定的文件
			file.transferTo(targetFile);
			pi.setPic(fileName);
			productInfoService.modifyProductInfo(pi);
			return "{\"success\":\"true\",\"message\":\"商品修改成功\"}";
		} catch (Exception e) {
			return "{\"success\":\"false\",\"message\":\"商品修改失敗\"}";
		}
	}

	// 商品下架(刪除商品)
	@RequestMapping(value = "/deleteProduct", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String deleteProduct(@RequestParam(value = "id") String id, @RequestParam(value = "flag") String flag) {
		String str = "";
		try {
			productInfoService.modifyStatus(id.substring(0, id.length() - 1), Integer.parseInt(flag));
			str = "{\"success\":\"true\",\"message\":\"刪除成功\"}";
		} catch (Exception e) {
			str = "{\"success\":\"false\",\"message\":\"刪除失敗\"}";
		}
		return str;
	}
	
	// 獲取在售商品列表
	@ResponseBody
	@RequestMapping("/getOnSaleProduct")
	public List<ProductInfo> getOnSaleProduct() {
		List<ProductInfo> piList = productInfoService.getOnSaleProduct();
		return piList;
	}
	
	// 根據商品id獲取商品對象
	@ResponseBody
	@RequestMapping("/getPriceById")
	public String getPriceById(@RequestParam(value = "pid") String pid) {
		if (pid != null && !"".equals(pid)) {
			ProductInfo pi = productInfoService.getProductInfoById(Integer.parseInt(pid));
			return pi.getPrice() + "";
		}else{
			return "";
		}
	}

}

在這裏插入圖片描述

添加控制器類TypeController

package com.ecpbm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ecpbm.pojo.Type;
import com.ecpbm.service.TypeService;

@Controller
@RequestMapping("/type")
public class TypeController {
	@Autowired
	private TypeService typeService;

	@RequestMapping("/getType/{flag}")
	@ResponseBody
	public List<Type> getType(@PathVariable("flag") Integer flag) {
		List<Type> typeList = typeService.getAll();
		if (flag == 1) {
			Type t = new Type();
			t.setId(0);
			t.setName("請選擇...");
			typeList.add(0, t);
		}
		return typeList;
	}

	@RequestMapping(value = "/addType", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String addType(Type type) {
		try {
			typeService.addType(type);
			return "{\"success\":\"true\",\"message\":\"添加成功\"}";
		} catch (Exception e) {
			return "{\"success\":\"false\",\"message\":\"添加失敗\"}";
		}
	}

	@RequestMapping(value = "/updateType", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String updateType(Type type) {
		try {
			typeService.updateType(type);
			return "{\"success\":\"true\",\"message\":\"修改成功\"}";
		} catch (Exception e) {
			return "{\"success\":\"false\",\"message\":\"修改失敗\"}";
		}
	}

}

9.訂單管理

creatorder.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'createorder.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>

	<!-- 定義table,用於創建easy ui的datagrid控件 -->
	<table id="odbox"></table>

	<!-- 創建datagrid控件的工具欄 -->
	<div id="ordertb" style="padding: 2px 5px;">
		<a href="javascript:void(0)" class="easyui-linkbutton"
			iconCls="icon-add" plain="true" onclick="addOrderDetail();">添加訂單明細</a><a
			href="javascript:void(0)" class="easyui-linkbutton"
			iconCls="icon-save" plain="true" onclick="saveorder();">保存訂單</a><a
			href="javascript:void(0)" class="easyui-linkbutton"
			iconCls="icon-remove" plain="true" onclick="removeOrderDetail();">刪除訂單明細</a>
	</div>

	<!-- 創建訂單主表錄入佈局 -->
	<div id="divOrderInfo">
		<div style="padding: 3px">
			客戶名稱&nbsp;<input style="width: 115px;" id="create_uid"
				class="easyui-combobox" name="create_uid" value="0"
				data-options="valueField:'id',textField:'userName',url:'userinfo/getValidUser'">&nbsp;&nbsp;&nbsp;
			訂單金額&nbsp;<input type="text" name="create_orderprice"
				id="create_orderprice" class="easyui-textbox" readonly="readonly"
				style="width: 115px" /> &nbsp;&nbsp;
		</div>
		<div style="padding: 3px">
			訂單日期&nbsp;<input type="text" name="create_ordertime"
				id="create_ordertime" class="easyui-datebox" style="width: 115px"
				value="<%=new Date().toLocaleString()%>" /> &nbsp;&nbsp;
			訂單狀態&nbsp;<select id="create_status" class="easyui-combobox"
				name="create_status" style="width: 115px;">
				<option value="未付款" selected>未付款</option>
				<option value="已付款">已付款</option>
				<option value="待發貨">待發貨</option>
				<option value="已發貨">已發貨</option>
				<option value="已完成">已完成</option>
			</select>
		</div>
	</div>

<script type="text/javascript">	      
	var $odbox = $('#odbox');
	$(function() {
		$odbox.datagrid({
			rownumbers : true,
			singleSelect : false, 
			fit : true,
			toolbar : '#ordertb',
			header : '#divOrderInfo',
			columns : [ [ {
				title : '序號',
				field : '',
				align : 'center',
				checkbox : true
			}, {
				field : 'pid',
				title : '商品名稱',
				width : 300,
				editor : {
					type : 'combobox',
					options : {
						valueField : 'id',
						textField : 'name',
						url : 'productinfo/getOnSaleProduct',
						onChange: function (newValue, oldValue) {
	                       var rows = $odbox.datagrid('getRows');      
	                       var orderprice=0;                     
	                       for (var i = 0; i < rows.length; i++) {                                          
	                           var pidEd = $('#odbox').datagrid('getEditor', {
	                               index: i,
	                               field: 'pid'
	                           });
	                           var priceEd = $('#odbox').datagrid('getEditor', {
	                               index: i,
	                               field: 'price'
	                           });
	                           var totalpriceEd = $('#odbox').datagrid('getEditor', {
	                               index: i,
	                               field: 'totalprice'
	                           });
	                           var numEd = $('#odbox').datagrid('getEditor', {
	                               index: i,
	                               field: 'num'
	                           });
	                           if (pidEd != null){
	                           	var pid=$(pidEd.target).combobox('getValue');                                     	
	                           	$.ajax({
								  type: 'POST',
								  url: 'productinfo/getPriceById',
								  data: {pid : pid},
								  success:  function(result) {
										$(priceEd.target).numberbox('setValue',result);
										$(totalpriceEd.target).numberbox('setValue',result * $(numEd.target).numberbox('getValue'));
										orderprice=Number(orderprice)+Number($(totalpriceEd.target).numberbox('getValue'));
								  },
								  dataType: 'json',
								  async : false
								});
	                          }
	                       }
	                       $("#create_orderprice").textbox("setValue",orderprice);
	                    }
					}
				}
			}, {
				field : 'price',
				title : '單價',
				width : 80,
				editor: {
					type : "numberbox",		
					options: {
						editable : false
					}	
				}					
			} , {
				field : 'num',
				title : '數量',
				width : 50,
				editor : {
					type : 'numberbox',
					options :{
						onChange: function (newValue, oldValue) {
	                        var rows = $odbox.datagrid('getRows');
	                        var orderprice=0;  
	                        for (var i = 0; i < rows.length; i++) { 
	                            var priceEd = $('#odbox').datagrid('getEditor', {
	                                index: i,
	                                field: 'price'
	                            });
	                            var totalpriceEd = $('#odbox').datagrid('getEditor', {
	                                index: i,
	                                field: 'totalprice'
	                            });
	                            var numEd = $('#odbox').datagrid('getEditor', {
	                                index: i,
	                                field: 'num'
	                            });
	                            $(totalpriceEd.target).numberbox('setValue',$(priceEd.target).numberbox('getValue') * $(numEd.target).numberbox('getValue'));
	                            orderprice=Number(orderprice)+Number($(totalpriceEd.target).numberbox('getValue'));
	                        }
	                        $("#create_orderprice").textbox("setValue",orderprice);
						}
					}
	             }
			}, {
				field : 'totalprice',
				title : '小計',
				width : 100,
				editor: {
					type : "numberbox",		
					options: {
						editable : false
					}	
				}	
			}  ] ]
		});
	});

		// datagrid中添加記錄行
		function addOrderDetail() {
			$odbox.datagrid('appendRow', {
				num : '1',
				price : '0',
				totalprice : '0'
			});
			var rows = $odbox.datagrid('getRows');
			// 讓添加的行處於可編輯狀態
			$odbox.datagrid('beginEdit', rows.length - 1);
		}

		// datagrid中刪除記錄行
		function removeOrderDetail() {
		    // 獲取所選擇的行記錄
			var rows = $odbox.datagrid('getSelections');
			if (rows.length > 0) {
				// 獲取“訂單金額”文本域的值
				var create_orderprice =  $("#create_orderprice").textbox("getValue");	
				// 遍歷選中的行記錄,以更新訂單金額		
				for (var i = 0; i < rows.length; i++) {
					var index = $odbox.datagrid('getRowIndex', rows[i]);
					var totalpriceEd = $('#odbox').datagrid('getEditor', {
                          index: index,
                          field: 'totalprice'
		             });	             
					create_orderprice = create_orderprice - Number($(totalpriceEd.target).numberbox('getValue'));
					$odbox.datagrid('deleteRow', index);
				}
				$("#create_orderprice").textbox("setValue",create_orderprice);
			} else {
				$.messager.alert('提示', '請選擇要刪除的行', 'info');
			}
		}

		// 保存訂單
		function saveorder() {	
		    // 獲取訂單客戶
			var uid = $("#create_uid").combobox("getValue");
			if(uid==0){
				$.messager.alert('提示', '請選擇客戶名稱', 'info');
			} else {
				// 取消datagrid控件的行編輯狀態
				create_endEdit();
				// 定義orderinfo存放訂單主表數據
				var orderinfo = [];
				// 獲取訂單時間
				var ordertime = $("#create_ordertime").datebox("getValue");
				// 獲取訂單狀態
				var status = $("#create_status").combobox("getValue");				
				// 獲取訂單金額
				var orderprice = $("#create_orderprice").textbox("getValue");
				orderinfo.push({
					ordertime : ordertime,
					uid : uid,
					status : status,
					orderprice : orderprice
				});
				// 獲取訂單明細(即datagrid控件中的記錄)
				if ($odbox.datagrid('getChanges').length) {
					// 獲取datagrid控件中插入的記錄行
					var inserted = $odbox.datagrid('getChanges', "inserted");
					// 獲取datagrid控件中刪除的記錄行
					var deleted = $odbox.datagrid('getChanges', "deleted");
					// 獲取datagrid控件中更新的記錄行
					var updated = $odbox.datagrid('getChanges', "updated");							
					// 定義effectRow,保存inserted和orderinfo
					var effectRow = new Object();
					if (inserted.length) {
						effectRow["inserted"] = JSON.stringify(inserted);
					}					
					effectRow["orderinfo"] = JSON.stringify(orderinfo);
					// 提交請求
					$.post(
					"orderinfo/commitOrder",
					effectRow,
					function(data) {
						if (data == 'success') {
							$.messager.alert("提示", "創建成功!");
							$odbox.datagrid('acceptChanges');
							if ($('#tabs').tabs('exists', '創建訂單')) {
								$('#tabs').tabs('close', '創建訂單');
							}
							$("#orderDg").datagrid('reload'); 
						} else {
							$.messager.alert("提示", "創建失敗!");
						}
					});
				}
			}	

		}

		// 取消datagrid控件的行編輯狀態
		function create_endEdit() {
			var rows = $odbox.datagrid('getRows');
			for (var i = 0; i < rows.length; i++) {
				$odbox.datagrid('endEdit', i);
			}
		}
	</script>

</body>
</html>

searchorder.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'newslist.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
	<!-- 定義table, 用於創建Easy UI的datagrid控件 -->
	<table id="orderDg" class="easyui-datagrid"></table>
	
	<!-- 工具欄 -->
	<div id="orderTb" style="padding:2px 5px;">
	   <a href="javascript:void(0)" class="easyui-linkbutton" 
	      iconCls="icon-edit" plain="true" onclick="editOrder();">查看明細</a> 
	   <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove"
			onclick="removeOrder();" plain="true">刪除訂單</a>
	</div>
	
	<!-- 查詢表單 -->
	<div id="searchOrderTb" style="padding:2px 5px;">
		<form id="searchOrderForm">
			<div style="padding:3px">
				訂單編號&nbsp;<input class="easyui-textbox" name="search_oid"
					id="search_oid" style="width:110px" />
			</div>
			<div style="padding:3px">
				客戶名稱&nbsp;<input style="width:115px;" id="search_uid"
					class="easyui-combobox" value="0" name="search_uid"
					data-options="valueField:'id',textField:'userName',url:'userinfo/getValidUser'">&nbsp;&nbsp;&nbsp;
				訂單狀態&nbsp;<select id="search_status" class="easyui-combobox" name="search_status" style="width:115px;">
					<option value="請選擇" selected>請選擇</option>
					<option value="未付款">未付款</option>
					<option value="已付款">已付款</option>
					<option value="待發貨">待發貨</option>
					<option value="已發貨">已發貨</option>
					<option value="已完成">已完成</option>
				</select>&nbsp;&nbsp;&nbsp; 訂單時間 &nbsp;<input class="easyui-datebox"
					name="orderTimeFrom" id="orderTimeFrom" style="width:115px;" /> ~
				<input class="easyui-datebox" name="orderTimeTo" id="orderTimeTo"
					style="width:115px;" /> <a href="javascript:void(0)"
					class="easyui-linkbutton" iconCls="icon-search" plain="true"
					onclick="searchOrderInfo();">查找</a>
			</div>
		</form>
	</div>


	<script type="text/javascript">
		$(function() {
			$('#orderDg').datagrid({
				singleSelect : false,
				url : 'orderinfo/list', //爲datagrid設置數據源
				queryParams : {}, //查詢條件
				pagination : true, //啓用分頁
				pageSize : 5, //設置初始每頁記錄數(頁大小)
				pageList : [ 5, 10, 15 ], //設置可供選擇的頁大小
				rownumbers : true, //顯示行號
				fit : true, //設置自適應
				toolbar : '#orderTb', //爲datagrid添加工具欄
				header : '#searchOrderTb', //爲datagrid標頭添加搜索欄
				columns : [ [ { //編輯datagrid的列
					title : '序號',
					field : 'id',
					align : 'center',
					checkbox : true
				}, {
					field : 'ui',
					title : '訂單客戶',
					formatter : function(value, row, index) {
						if (row.ui) {
							return row.ui.userName;
						} else {
							return value;
						}
					},
					width : 100
				}, {
					field : 'status',
					title : '訂單狀態',
					width : 80
				}, {
					field : 'ordertime',
					title : '訂單時間',
					width : 100
				}, {
					field : 'orderprice',
					title : '訂單金額',
					width : 100
				} ] ]
			});
		});

		var urls;
		var data;
		
		// 刪除訂單
		function removeOrder() {
			// 獲取選中的訂單記錄行
			var rows = $("#orderDg").datagrid('getSelections');
			if (rows.length > 0) {
				$.messager.confirm('Confirm', '確認要刪除麼?', function(r) {
					if (r) {
						var ids = "";
						// 獲取選中訂單記錄的訂單id, 保存到ids中
						for (var i = 0; i < rows.length; i++) {
							ids += rows[i].id + ",";
						}
						// 發送請求
						$.post('orderinfo/deleteOrder', {
							oids : ids
						}, function(result) {
							if (result.success == 'true') {
								$("#orderDg").datagrid('reload'); 
								$.messager.show({
									title : '提示信息',
									msg : result.message
								});
							} else {
								$.messager.show({
									title : '提示信息',
									msg : result.message
								});
							}
						}, 'json');

					}
				});
			} else {
				$.messager.alert('提示', '請選擇要刪除的行', 'info');
			}
		}		

		// 查看明細
		function editOrder() {
		    var rows = $("#orderDg").datagrid('getSelections');
			if (rows.length > 0) {
				var row = $("#orderDg").datagrid("getSelected");
				if ($('#tabs').tabs('exists', '訂單明細')) {
					$('#tabs').tabs('close', '訂單明細');
				}
				$('#tabs').tabs('add', {
					title : "訂單明細",
					href : 'orderinfo/getOrderInfo?oid=' + row.id,
					closable : true
				});
			}else {
				$.messager.alert('提示', '請選擇要修改的訂單', 'info');
			}
		}

	// 查詢訂單
	function searchOrderInfo() {			
		var oid = $('#search_oid').val();
		var status = $('#search_status').combobox("getValue");
		var uid = $('#search_uid').combobox("getValue");
		var orderTimeFrom = $("#orderTimeFrom").datebox("getValue");
		var orderTimeTo = $("#orderTimeTo").datebox("getValue");
		$('#orderDg').datagrid('load', {
			id : oid,
			status : status,
			uid : uid,
			orderTimeFrom : orderTimeFrom,
			orderTimeTo : orderTimeTo
		});
	}
	</script>
</body>
</html>

UserInfoController

package com.ecpbm.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ecpbm.pojo.Pager;
import com.ecpbm.pojo.UserInfo;
import com.ecpbm.service.UserInfoService;

@Controller
@RequestMapping("/userinfo")
public class UserInfoController {

	@Autowired
	UserInfoService userInfoService;

	@RequestMapping("/getValidUser")
	@ResponseBody
	public List<UserInfo> getValidUser() {
		List<UserInfo> uiList = userInfoService.getValidUser();
		UserInfo ui = new UserInfo();
		ui.setId(0);
		ui.setUserName("請選擇...");
		uiList.add(0, ui);
		return uiList;
	}

	@RequestMapping("/list")
	@ResponseBody
	public Map<String, Object> userlist(Integer page, Integer rows, UserInfo userInfo) {
		// 創建分頁類對象
		Pager pager = new Pager();
		pager.setCurPage(page);
		pager.setPerPageRows(rows);
		// 創建對象params,封裝查詢條件
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userInfo", userInfo);
		// 根據查詢條件,獲取客戶記錄數
		int totalCount = userInfoService.count(params);
		// 根據查詢條件,分頁獲取客戶列表
		List<UserInfo> userinfos = userInfoService.findUserInfo(userInfo, pager);
		// 創建對象result,保存查詢結果數據
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("total", totalCount);
		result.put("rows", userinfos);
		return result;
	}

	// 更新客戶狀態
	@RequestMapping(value = "/setIsEnableUser", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String setIsEnableUser(@RequestParam(value = "uids") String uids,
			@RequestParam(value = "flag") String flag) {
		try {
			userInfoService.modifyStatus(uids.substring(0, uids.length() - 1), Integer.parseInt(flag));
			return "{\"success\":\"true\",\"message\":\"更改成功\"}";
		} catch (Exception e) {
			return "{\"success\":\"false\",\"message\":\"更改失敗\"}";
		}
	}

}

OrderInfoController

package com.ecpbm.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ecpbm.pojo.OrderDetail;
import com.ecpbm.pojo.OrderInfo;
import com.ecpbm.pojo.Pager;
import com.ecpbm.service.OrderInfoService;
import com.ecpbm.service.ProductInfoService;
import com.ecpbm.service.UserInfoService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.JsonParseException;

@Controller
@RequestMapping("/orderinfo")
public class OrderInfoController {
	@Autowired
	OrderInfoService orderInfoService;
	@Autowired
	UserInfoService userInfoService;
	@Autowired
	ProductInfoService productInfoService;

	// 分頁顯示
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(Integer page, Integer rows, OrderInfo orderInfo) {
		// 初始化一個分頁類對象pager
		Pager pager = new Pager();
		pager.setCurPage(page);
		pager.setPerPageRows(rows);
		// 創建對象params,用於封裝查詢條件
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderInfo", orderInfo);
		// 獲取滿足條件的訂單總數
		int totalCount = orderInfoService.count(params);
		// 獲取滿足條件的訂單列表
		List<OrderInfo> orderinfos = orderInfoService.findOrderInfo(orderInfo, pager);
		// 創建result對象,保存查詢結果數據
		Map<String, Object> result = new HashMap<String, Object>(2);
		result.put("total", totalCount);
		result.put("rows", orderinfos);
		return result;
	}

	// 保存訂單
	@ResponseBody
	@RequestMapping(value = "/commitOrder")
	public String commitOrder(String inserted, String orderinfo)
			throws JsonParseException, JsonMappingException, IOException {
		try {
			// 創建ObjectMapper對象,實現JavaBean和JSON的轉換
			ObjectMapper mapper = new ObjectMapper();
			// 設置輸入時忽略在JSON字符串中存在但Java對象實際沒有的屬性
			mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
			mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
			// 將json字符串orderinfo轉換成JavaBean對象(訂單信息)
			OrderInfo oi = mapper.readValue(orderinfo, OrderInfo[].class)[0];
			// 保存訂單信息
			orderInfoService.addOrderInfo(oi);
			// 將json字符串轉換成List<OrderDetail>集合(訂單明細信息)
			List<OrderDetail> odList = mapper.readValue(inserted, new TypeReference<ArrayList<OrderDetail>>() {
			});
			// 給訂單明細對象的其他屬性賦值
			for (OrderDetail od : odList) {
				od.setOid(oi.getId());
				// 保存訂單明細
				orderInfoService.addOrderDetail(od);
			}
			return "success";
		} catch (Exception e) {
			return "failure";
		}
	}

	// 根據訂單id號獲取要查看的訂單對象, 再返回訂單明細頁
	@RequestMapping("/getOrderInfo")
	public String getOrderInfo(String oid, Model model) {
		OrderInfo oi = orderInfoService.getOrderInfoById(Integer.parseInt(oid));
		model.addAttribute("oi", oi);
		return "orderdetail";
	}

	// 根據訂單id號獲取訂單明細列表
	@RequestMapping("/getOrderDetails")
	@ResponseBody
	public List<OrderDetail> getOrderDetails(String oid) {
		List<OrderDetail> ods = orderInfoService.getOrderDetailByOid(Integer.parseInt(oid));
		for (OrderDetail od : ods) {
			// od.setPid(od.getPi().getId());
			od.setPrice(od.getPi().getPrice());
			od.setTotalprice(od.getPi().getPrice() * od.getNum());
		}
		return ods;
	}

	// 刪除訂單
	@ResponseBody
	@RequestMapping(value = "/deleteOrder", produces = "text/html;charset=UTF-8")
	public String deleteOrder(String oids) {
		String str = "";
		try {
			oids = oids.substring(0, oids.length() - 1);
			String[] ids = oids.split(",");
			for (String id : ids) {
				orderInfoService.deleteOrder(Integer.parseInt(id));
			}
			str = "{\"success\":\"true\",\"message\":\"刪除成功!\"}";
		} catch (Exception e) {
			str = "{\"success\":\"false\",\"message\":\"刪除失敗!\"}";
		}
		return str;
	}

}

10.客戶管理

userlist.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<%
  if(session.getAttribute("admin")==null)
  	response.sendRedirect("/digital-um/admin_login.jsp");
 %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'newslist.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

</head>

<body>
    <!-- 創建一個table -->
	<table id="userListDg" class="easyui-datagrid"></table>
	
	<!-- 創建工具欄 -->
	<div id="userListTb" style="padding:2px 5px;"><a href="javascript:void(0)"
		class="easyui-linkbutton" iconCls="icon-edit" plain="true"
		onclick="SetIsEnableUser(1);">啓用客戶</a> <a href="javascript:void(0)"
		class="easyui-linkbutton" iconCls="icon-remove"
		onclick="SetIsEnableUser(0);" plain="true">禁用客戶</a>
	</div>
	
	<!-- 創建搜索欄 -->
	<div id="searchUserListTb" style="padding:4px 3px;">
		<form id="searchUserListForm">
			<div style="padding:3px ">
				客戶名稱&nbsp;&nbsp;<input class="easyui-textbox" name="search_userName"
					id="search_userName" style="width:110px" /><a href="javascript:void(0)"
					class="easyui-linkbutton" iconCls="icon-search" plain="true"
					onclick="searchUserInfo();">查找</a>
			</div>			
		</form>
	</div>

	<script type="text/javascript">
		$(function() {
			$('#userListDg').datagrid({
				singleSelect : false,
				url : 'userinfo/list',
				queryParams : {}, //查詢條件
				pagination : true, //啓用分頁
				pageSize : 5, //設置初始每頁記錄數(頁大小)
				pageList : [ 5, 10, 15 ], //設置可供選擇的頁大小
				rownumbers : true, //顯示行號
				fit : true, //設置自適應
				toolbar : '#userListTb', //爲datagrid添加工具欄
				header : '#searchUserListTb', //爲datagrid標頭添加搜索欄
				columns : [ [ { //編輯datagrid的列
					title : '序號',
					field : 'id',
					align : 'center',
					checkbox : true
				}, {
					field : 'userName',
					title : '登錄名',					
					width : 100
				}, {
					field : 'realName',
					title : '真實姓名',
					width : 80
				}, {
					field : 'sex',
					title : '性別',
					width : 100
				}, {
					field : 'address',
					title : '住址',
					width : 200
				} , {
					field : 'email',
					title : '郵箱',
					width : 150
				} , {
					field : 'regDate',
					title : '註冊日期',
					width : 100
				} , {
					field : 'status',
					title : '客戶狀態',
					width : 100,
					formatter : function(value, row, index) {
						if (row.status==1) {
							return "啓用";
						} else {
							return "禁用";
						}
					}
				} ] ]
			});
		});

		var urls;
		var data;
		
		function searchUserInfo() {
			var userName = $('#search_userName').textbox("getValue");
			$('#userListDg').datagrid('load', {
				userName : userName
			});
		}
		
		
		// 設置啓用或禁用客戶
		function SetIsEnableUser(flag) {
			var rows = $("#userListDg").datagrid('getSelections');
			if (rows.length > 0) {
				$.messager.confirm('Confirm', '確認要設置麼?', function(r) {
					if (r) {
						var uids = "";
						for (var i = 0; i < rows.length; i++) {
							uids += rows[i].id + ",";
						}						
						$.post('userinfo/setIsEnableUser', {
							uids : uids,
							flag : flag
						}, function(result) {
							if (result.success == 'true') {
								$("#userListDg").datagrid('reload'); 
								$.messager.show({
									title : '提示信息',
									msg : result.message
								});
							} else {
								$.messager.show({
									title : '提示信息',
									msg : result.message
								});
							}
						}, 'json');

					}
				});
			} else {
				$.messager.alert('提示', '請選擇要啓用或禁用的客戶', 'info');
			}
		}
		
	</script>
</body>
</html>

這兩張只是簡單的把代碼先貼上來,運行下看看流程,然後下一章開始會細細拆分每個功能。

用到的工具

ProcessOn:畫圖
SQLyog:圖形化管理MYSQL數據庫的工具
eclipse
Spring,Spring MVC MyBatis
EasyUi

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