SSM校園商鋪平台(五)
-
- 1.店鋪資訊編輯功能的實作
-
- 1.1 dao層實作
- 1.2 service層的實作
- 1.3 controller層的實作
- 1.4 前端實作
- 2. 店鋪清單的展示
-
- 2.1 dao層(分頁查詢店鋪)
- 2.2 service層實作
- 2.3 controller層
- 2.4 店鋪清單展示前端
- 2.5 店鋪管理前端
1.店鋪資訊編輯功能的實作
- 實作單個店鋪的資訊擷取
- 實作對店鋪資訊進行修改
1.1 dao層實作
在shopDao接口添加方法:
// 通過id查詢店鋪
Shop queryByShopId(long shopId);
在mapper中shopDao.xml添加查詢語句:
由于Shop類中不僅僅有基本資料類型,還關聯了其他類。是以我們需要寫一個resultMap作為傳回值。
與shop關聯的3個類:
private Area area;
private PersonInfo owner;
private ShopCategory shopCategory;
resultMap的寫法:
- 指定我們傳回類Shop的type和resultMapid
- 再指定Shop的主鍵也就是id,其中column指的是資料庫中tb_shop表的shop_id, property指的是Shop.java類中shopId,将其關聯起來
- 再指定其他基本類型資料庫字段與Shop類的屬性關聯
- 但是對于資料庫中的area_id,shop_category_id和user_id在Shop類中沒有對應的屬性,而是3個對象。是以我們需要将對象的屬性和資料庫字段關聯起來
- 采用association關聯對象字段column指的是資料庫字段area_id,property指的是Shop類中的屬性area對象。
- 再指定該Area類下面的關聯:包括主鍵id,和result
- 這樣就将這三張表關聯起來了
- 再select語句中,parameterType指的是輸入參數類型
<!-- 查詢店鋪 -->
<resultMap type="com.imooc.o2o.entity.Shop" id="shopMap">
<id column="shop_id" property="shopId"/>
<result column="shop_name" property="shopName" />
<result column="shop_desc" property="shopDesc" />
<result column="shop_addr" property="shopAddr" />
<result column="phone" property="phone" />
<result column="shop_img" property="shopImg" />
<result column="priority" property="priority" />
<result column="create_time" property="createTime" />
<result column="last_edit_time" property="lastEditTime" />
<result column="enable_status" property="enableStatus" />
<result column="advice" property="advice" />
<association property="area" column="area_id" javaType="com.imooc.o2o.entity.Area">
<id column="area_id" property="areaId"/>
<result column="area_name" property="areaName"/>
</association>
<association property="shopCategory" column="shop_category_id" javaType="com.imooc.o2o.entity.ShopCategory">
<id column="shop_category_id" property="shopCategoryId"/>
<result column="shop_category_name" property="shopCategoryName"/>
</association>
<association property="owner" column="user_id" javaType="com.imooc.o2o.entity.PersonInfo">
<id column="user_id" property="userId"/>
<result column="name" property="name"/>
</association>
</resultMap>
<select id="queryByShopId" resultMap="shopMap" parameterType="Long">
SELECT
s.shop_id,
s.shop_name,
s.shop_desc,
s.shop_addr,
s.phone,
s.shop_img,
s.priority,
s.create_time,
s.last_edit_time,
s.enable_status,
s.advice,
a.area_id,
a.area_name,
sc.shop_category_id,
sc.shop_category_name
FROM
tb_shop s,
tb_area a,
tb_shop_category sc
WHERE
s.area_id = a.area_id
AND
s.shop_category_id = sc.shop_category_id
AND
s.shop_id = #{shopId}
</select>
1.2 service層的實作
1.2.1 查詢shop
在Shopservice接口和接口實作類中添加方法:
//查詢shop
@Override
public Shop getByShopId(long shopId) {
return shopDao.queryByShopId(shopId);
}
1.2.2 更新shop
- 更新前都要先判斷輸入的shop和shopId是否為空
- 判斷是否需要更新圖檔,如果以前的shop是有圖檔的就将以前的圖檔和所在的檔案夾删除,再添加圖檔;如果以前沒有添加圖檔,直接addShopImg
- 删除圖檔和檔案夾需要調用deleteFileOrPath方法
- 更新店鋪資訊
public ShopExecution modifyShop(Shop shop, InputStream shopImgInputStream, String fileName) throws ShopOperationException{
//更新之前都會先進行查詢,如果查詢到的shop為空
if(shop==null || shop.getShopId()==null) {
return new ShopExecution(ShopStateEnum.NULL_SHOP);
}
else {
try {
//判斷是否需要處理圖檔
if(shopImgInputStream != null) {
Shop tempShop = shopDao.queryByShopId(shop.getShopId());
if(tempShop.getShopImg() != null) {
ImageUtil.deleteFileOrPath(tempShop.getShopImg());
}
addShopImg(tempShop, shopImgInputStream, fileName);
}
//更新店鋪資訊
shop.setLastEditTime(new Date());
int effectedNum = shopDao.updateShop(shop);
if(effectedNum < 0) {
return new ShopExecution(ShopStateEnum.INNER_ERROR);
}
else {
shop = shopDao.queryByShopId(shop.getShopId());
return new ShopExecution(ShopStateEnum.SUCCESS,shop);
}
} catch (Exception e) {
throw new ShopOperationException("modifyShop error:"+e.getMessage());
}
}
}
删除圖檔和檔案夾的工具類方法:
/*
* 如果storePath是檔案路徑則删除該檔案
* 如果storePath是目錄路徑則删除該目錄下所有檔案
*/
public static void deleteFileOrPath(String storePath) {
File file = new File(PathUtil.getImgBasePath() + storePath);
if (file.exists()) {
if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
}
file.delete();
}
}
1.3 controller層的實作
//更改店鋪
@RequestMapping(value="/registershop",method= {RequestMethod.POST})
@ResponseBody
private Map<String,Object> moodifyShop(HttpServletRequest request){
Map<String,Object> modelMap = new HashMap<>();
//判斷驗證碼是否正确
System.out.println(CodeUtil.cheackVerifyCode(request));
if(!CodeUtil.cheackVerifyCode(request)) {
modelMap.put("success", false);
modelMap.put("errMsg", "驗證碼錯誤");
return modelMap;
}
//1.接受并轉換相應的參數
String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
ObjectMapper mapper = new ObjectMapper();
Shop shop = null;
try {
//這是将字元串shopStr轉換成Shop.class類的JSON資料格式
shop = mapper.readValue(shopStr , Shop.class);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg",e.getMessage());
return modelMap;
}
//擷取前端傳遞的檔案流(圖檔)
CommonsMultipartFile shopImg = null;
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
//判斷上傳的request是否含有圖檔,是就将圖檔指派給shopImg
if(commonsMultipartResolver.isMultipart(request)) {
MultipartHttpServletRequest httpServletRequest = (MultipartHttpServletRequest) request;
shopImg = (CommonsMultipartFile) httpServletRequest.getFile("shopImg");
}
else {
modelMap.put("success", false);
modelMap.put("errMsg","上傳圖檔不能為空");
return modelMap;
}
//2.修改店鋪資訊
if(shop!=null && shop.getShopId()!=null) {
ShopExecution se;
try {
if(shopImg == null) {
se = shopService.modifyShop(shop, null, null);
}
else
se = shopService.modifyShop(shop, shopImg.getInputStream(),shopImg.getOriginalFilename());
if(se.getState()==ShopStateEnum.SUCCESS.getState()) {
modelMap.put("success", true);
}
else {
modelMap.put("success", false);
modelMap.put("errMsg", se.getStateInfo());
}
} catch (IOException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
}
}
else {
modelMap.put("success", false);
modelMap.put("errMsg","請輸入店鋪資訊");
return modelMap;
}
//3.傳回結果
return modelMap;
}
1.4 前端實作
- 取出url中的shopid,并查詢該id下的資訊顯示到前台
- 判斷是否需要送出shopid
//從url中取出shopid的值
var shopId = getQueryString('shopId');
//判斷shopid是否為空
var isEdit = shopId ? true : false;
//var shopInfoUrl = '/myo2o/shop/getshopbyid?shopId=1';
var shopInfoUrl = '/o2o/shop/getshopbyid?shopId=' + shopId;
//送出表單的url,如果是新增shop不變;如果是修改shop,editShopUrl需要改動
var editShopUrl = '/o2o/shop/registershop';
if (isEdit) {
editShopUrl = '/o2o/shop/modifyshop';
}
function getInfo(shopId) {
$.getJSON(shopInfoUrl, function(data) {
if (data.success) {
var shop = data.shop;
$('#shop-name').val(shop.shopName);
$('#shop-addr').val(shop.shopAddr);
$('#shop-phone').val(shop.phone);
$('#shop-desc').val(shop.shopDesc);
var shopCategory = '<option data-id="'
+ shop.shopCategory.shopCategoryId + '" selected>'
+ shop.shopCategory.shopCategoryName + '</option>';
var tempAreaHtml = '';
data.areaList.map(function(item, index) {
tempAreaHtml += '<option data-id="' + item.areaId + '">'
+ item.areaName + '</option>';
});
$('#shop-category').html(shopCategory);
$('#shop-category').attr('disabled','disabled');
$('#area').html(tempAreaHtml);
$('#area').attr('data-id',shop.areaId);
}
});
}
//該函數用于執行點選送出,就将前台資料送出到背景
$('#submit').click(function() {
var shop = {};
//判斷是否需要送出shopid
if(isEdit)
shop.shopId = shopId;
2. 店鋪清單的展示
2.1 dao層(分頁查詢店鋪)
- dao中的方法如果有多個參數或者參數是一個對象,mybatis必須使用@param來取,如果隻有一個參數則不需要
/**
* 分頁查詢店鋪,可輸入條件有(店鋪名,店鋪狀态,店鋪類别,區域id,owner)
* @param shopCondition
* @param rowIndex 從第幾行開始
* @param pageSize 傳回的資料條數
*
* @return
*/
List<Shop> queryShopList(@Param("shopCondition") Shop shopCondition,
@Param("rowIndex")int rowIndex,@Param("pageSize")int pageSize);
int queryShopCount(@Param("shopCondition") Shop shopCondition);
// 新增店鋪
int insertShop(Shop shop);
ShopDao.xml實作
- 通過and将多個查詢條件連接配接起來
<select id="queryShopList" resultMap="shopMap" parameterType="Long">
SELECT
s.shop_id,
s.shop_name,
s.shop_desc,
s.shop_addr,
s.phone,
s.shop_img,
s.priority,
s.create_time,
s.last_edit_time,
s.enable_status,
s.advice,
a.area_id,
a.area_name,
sc.shop_category_id,
sc.shop_category_name
FROM
tb_shop s,
tb_area a,
tb_shop_category sc
<where>
<if test="shopCondition.shopCategory != null
and shopCondition.shopCategory.shopCategoryId !=null">
and s.shop_category_id =
#{shopCondition.shopCategory.shopCategoryId}
</if>
<if test="shopCondition.area != null
and shopCondition.area.areaId !=null">
and s.shop_area_id =
#{shopCondition.area.areaId}
</if>
<if test="shopCondition.shopName!=null">
and s.shop_name like '%${shopCondition.shopName}%'
</if>
<if test="shopCondition.enableStatus !=null">
and s.shop_enableStatus = #{shopCondition.enableStatus}
</if>
<if test="shopCondition.owner !=null">
and s.owner_id = #{shopCondition.owner.userId}
</if>
and
s.area_id = a.area_id
and
s.shop_category_id = sc.shop_category_id
</where>
<!-- 分頁 -->
ORDER BY
s.priority DESC
LIMIT #{rowIndex},#{pageSize}
</select>
<select id="queryShopCount" resultType="int">
SELECT
count(1)
FROM
tb_shop s,
tb_area a,
tb_shop_category sc
<where>
<if test="shopCondition.shopCategory != null
and shopCondition.shopCategory.shopCategoryId !=null">
and s.shop_category_id =
#{shopCondition.shopCategory.shopCategoryId}
</if>
<if test="shopCondition.area != null
and shopCondition.area.areaId !=null">
and s.shop_area_id =
#{shopCondition.area.areaId}
</if>
<if test="shopCondition.shopName!=null">
and s.shop_name like '%${shopCondition.shopName}%'
</if>
<if test="shopCondition.enableStatus !=null">
and s.shop_enableStatus = #{shopCondition.enableStatus}
</if>
<if test="shopCondition.owner !=null">
and s.owner_id = #{shopCondition.owner.userId}
</if>
and
s.area_id = a.area_id
and
s.shop_category_id = sc.shop_category_id
</where>
</select>
2.2 service層實作
//分頁查詢店鋪
@Override
public ShopExecution getShopList(Shop shopCondition, int pageIndex, int pageSize) {
int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
List<Shop> shopList = shopDao.queryShopList(shopCondition, rowIndex, pageSize);
int count = shopDao.queryShopCount(shopCondition);
ShopExecution se = new ShopExecution();
if(shopList!=null) {
se.setShopList(shopList);
se.setCount(count);
}
else {
se.setState(ShopStateEnum.INNER_ERROR.getState());;
}
return se;
}
2.3 controller層
- 現根據輸入的使用者id user_id做跳轉,如果沒有user_id,跳轉到查詢頁面,如果有user_id跳轉到使用者管理界面
- 跳轉到使用者管理界面後,查詢該使用者建立的所有店鋪
//根據使用者資訊查詢使用者建立的店鋪
@RequestMapping(value = "/getshoplist",method = {RequestMethod.GET})
@ResponseBody
private Map<String,Object> getShopList(HttpServletRequest request){
Map<String,Object> modelMap = new HashMap<String, Object>();
PersonInfo user = new PersonInfo();
user.setUserId(1L);
user.setName("test");
//采用session來模拟使用者登陸
request.getSession().setAttribute("user",user);
user = (PersonInfo) request.getSession().getAttribute("user");
System.out.println(user);
try {
Shop shopCondition = new Shop();
shopCondition.setOwner(user);
ShopExecution se = shopService.getShopList(shopCondition, 0, 100);
modelMap.put("shopList", se.getShopList());
modelMap.put("user", user);
modelMap.put("success", true);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
}
return modelMap;
}
//店鋪管理,根據輸入的資訊做跳轉
@RequestMapping(value = "/getshopmanagementinfo",method = {RequestMethod.GET})
@ResponseBody
private Map<String,Object> getShopManageMentInfo(HttpServletRequest request){
Map<String,Object> modelMap = new HashMap<String, Object>();
long shopId = HttpServletRequestUtil.getLong(request, "shopId");
//如果前台沒有傳過來shopid
if(shopId < 0) {
Object currentShopObj = request.getSession().getAttribute("currentShop");
//檢查session中是否含有shopid
if(currentShopObj==null) {
modelMap.put("redirect", true);
modelMap.put("url", "/o2o/shop/shoplist");
}
else {
Shop currentShop = (Shop)currentShopObj;
modelMap.put("redirect", false);
modelMap.put("shopId", currentShop.getShopId());
}
}
//前台傳過來了shopid
else {
Shop currentShop = new Shop();
currentShop.setShopId(shopId);
request.getSession().setAttribute("currentShop", currentShop);
modelMap.put("redirect", false);
}
return modelMap;
}
2.4 店鋪清單展示前端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>商店清單</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="stylesheet" href="//g.alicdn.com/msui/sm/0.6.2/css/sm.min.css">
<link rel="stylesheet" href="//g.alicdn.com/msui/sm/0.6.2/css/sm-extend.min.css">
<link rel="stylesheet" href="../resources/css/shop/shoplist.css">
</head>
<body>
<header class="bar bar-nav">
<h1 class="title">商店清單</h1>
</header>
<div class="content">
<div class="content-block">
<p>你好,<span id="user-name"></span></p>
<div class="row row-shop">
<div class="col-40">商店名稱</div>
<div class="col-40">狀态</div>
<div class="col-20">操作</div>
</div>
<div class="shop-wrap">
</div>
</div>
<div class="content-block">
<div class="row">
<div class="col-50">
<a href="" id="log-out"
class="button button-big button-fill button-danger">退出系統</a>
</div>
<div class="col-50">
<a href="/myo2o/shop/changepsw" class="button button-big button-fill button-success">修改密碼</a>
</div>
</div>
</div>
</div>
<script type='text/javascript' src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script>
<script type='text/javascript' src='//g.alicdn.com/msui/sm/0.6.2/js/sm.min.js' charset='utf-8'></script>
<script type='text/javascript' src='//g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script>
<script type='text/javascript' src='../resources/js/shop/shoplist.js' charset='utf-8'></script>
</body>
</html>
$(function () {
function getlist(e) {
$.ajax({
url : "/o2o/shop/getshoplist",
type : "get",
dataType : "json",
success : function(data) {
if (data.success) {
handleList(data.shopList);
handleUser(data.user);
}
}
});
}
function handleUser(data) {
$('#user-name').text(data.name);
}
function handleList(data) {
var html = '';
data.map(function (item, index) {
html += '<div class="row row-shop"><div class="col-40">'+ item.shopName +'</div><div class="col-40">'+ shopStatus(item.enableStatus) +'</div><div class="col-20">'+ goShop(item.enableStatus, item.shopId) +'</div></div>';
});
$('.shop-wrap').html(html);
}
function goShop(status, id) {
if (status != 0 && status != -1) {
return '<a href="/o2o/shopadmin/shopmanage?shopId='+ id +'">進入</a>';
} else {
return '';
}
}
function shopStatus(status) {
if (status == 0) {
return '稽核中';
} else if (status == -1) {
return '店鋪非法';
} else {
return '稽核通過';
}
}
$('#log-out').click(function () {
$.ajax({
url : "/myo2o/shop/logout",
type : "post",
contentType : false,
processData : false,
cache : false,
success : function(data) {
if (data.success) {
window.location.href = '/myo2o/shop/ownerlogin';
}
},
error : function(data, error) {
alert(error);
}
});
});
getlist();
});
2.5 店鋪管理前端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>商店管理</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="stylesheet" href="//g.alicdn.com/msui/sm/0.6.2/css/sm.min.css">
<link rel="stylesheet" href="//g.alicdn.com/msui/sm/0.6.2/css/sm-extend.min.css">
<link rel="stylesheet" href="../resources/css/shop/shopmanage.css">
</head>
<body>
<header class="bar bar-nav">
<h1 class="title">商店管理</h1>
</header>
<div class="content">
<div class="content-block">
<div class="row">
<div class="col-50 mb">
<a href="/o2o/shopadmin/shopedit" class="button button-big button-fill">商鋪資訊</a>
</div>
<div class="col-50 mb">
<a href="/myo2o/shop/productmanage" class="button button-big button-fill">商品管理</a>
</div>
<div class="col-50 mb">
<a href="/myo2o/shop/productcategorymanage" class="button button-big button-fill">類别管理</a>
</div>
<div class="col-50 mb">
<a href="/myo2o/shop/awardmanage" class="button button-big button-fill">獎品管理</a>
</div>
<div class="col-50 mb">
<a href="/myo2o/shop/productbuycheck" class="button button-big button-fill">消費記錄</a>
</div>
<div class="col-50 mb">
<a href="/myo2o/shop/awarddelivercheck" class="button button-big button-fill">積分對換</a>
</div>
<div class="col-50 mb">
<a href="/myo2o/shop/usershopcheck" class="button button-big button-fill">顧客積分</a>
</div>
<div class="col-50 mb">
<a href="/myo2o/shop/shopauthmanage" class="button button-big button-fill">授權管理</a>
</div>
<div class="col-100 mb">
<a href="/o2o/shopadmin/shoplist" class="button button-big button-fill button-danger">傳回</a>
</div>
</div>
</div>
</div>
<script type='text/javascript' src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script>
<script type='text/javascript' src='//g.alicdn.com/msui/sm/0.6.2/js/sm.min.js' charset='utf-8'></script>
<script type='text/javascript' src='//g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script>
<script type='text/javascript' src='../resources/js/shop/shopmanage.js' charset='utf-8'></script>
</body>
</html>
$(function){
var shopId = getQueryString('shopId');
var shopInfoUrl = '/o2o/shop/getshopmanagementinfo?shopId='+shopId;
$.getJSON(shopInfoUrl,function(data)){
if(data.redirect){
window.location.href = data.url;
}
else{
if(data.shopId!=undefined && data.shopId!=null){
shopId = data.shopId;
}
$('#shopInfo').attr('herf','/o2o/shop/shopedit?shopId='+shopId);
}
}
}