SSM到Spring Boot-從零開發校園商鋪平臺六(店鋪編輯和列表功能)

店鋪信息編輯之Dao層開發

ShopDao

     /**
     * 通過owner id 查詢店鋪
     */
    Shop queryByShopId(long shopId);

ShopDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.o2o.dao.ShopDao">
    <resultMap id="shopMap" type="com.imooc.o2o.entity.Shop">
        <id column="shop_id" property="shopId" />
        <result column="owner_id" property="ownerId" />
        <result column="shop_category_id" property="shopCategoryId" />
        <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="longitude" property="longitude" />
        <result column="latitude" property="latitude" />
        <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">
        <!-- 具體的sql -->
        SELECT
        s.shop_id,
        s.shop_name,
        s.shop_desc,
        s.shop_addr,
        s.phone,
        s.shop_img,
        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.shop_category_id =sc.shop_category_id
        and s.shop_id = #{shopId}
    </select>
    <insert id="insertShop" useGeneratedKeys="true" keyColumn="shop_id"
            keyProperty="shopId">
        insert into tb_shop(owner_id,area_id,shop_category_id,shop_name,shop_desc,shop_addr,phone,
        shop_img,priority,create_time,last_edit_time,enable_status,advice)
        values (
        #{owner.userId},#{area.areaId},#{shopCategory.shopCategoryId},#{shopName},#{shopDesc},
        #{shopAddr},#{phone},#{shopImg},#{priority},#{createTime},#{lastEditTime},#{enableStatus},
        #{advice}
        )
    </insert>

    <update id="updateShop" parameterType="com.imooc.o2o.entity.Shop">
        update tb_shop
        <set>
            <if test="shopName!=null">shop_name=#{shopName},</if>
            <if test="shopDesc != null">shop_desc=#{shopDesc},</if>
            <if test="shopAddr != null">shop_addr=#{shopAddr},</if>
            <if test="phone != null">phone=#{phone},</if>
            <if test="shopImg != null">shop_img=#{shopImg},</if>
            <if test="priority != null">priority=#{priority},</if>
            <if test="lastEditTime != null">last_edit_time=#{lastEditTime},</if>
            <if test="enableStatus != null">enable_status=#{enableStatus},</if>
            <if test="advice != null">advice=#{advice},</if>
            <if test="area != null">area_id=#{area.areaId},</if>
            <if test="shopCategory != null">shop_category_id=#{shopCategory.shopCategoryId}</if>
        </set>
        where shop_id=#{shopId}
    </update>
</mapper>

Test

    @Test
    public void queryByShopId(){
        long shopId=1;
        Shop shop = shopDao.queryByShopId(shopId);
        System.out.println("areaId:"+shop.getShopId());
        System.out.println("areaName:"+shop.getShopName());
    }

店鋪信息編輯之Serice實現

shopService

    /**
     * 查詢指定店鋪信息
     * @param shopId
     * @return
     */
    Shop getByShopId(long shopId);

    /**
     * 更新店鋪信息(從店家角度)
     * @param shop
     * @param shopImg
     * @return
     * @throws RuntimeException
     */
    ShopExecution modifyShop(Shop shop, InputStream shopImgInputStream,
                             String fileName) throws RuntimeException;

shopServiceImpl

@Override
    public Shop getByShopId(long shopId) {
        return shopDao.queryByShopId(shopId);
    }

    @Override
    public ShopExecution modifyShop(Shop shop,
                                    InputStream shopImgInputStream,
                                    String fileName) throws RuntimeException {
        if(shop ==null||shop.getShopId()==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOPID);
        }else{
            try {
                //1.判斷是否需要處理圖片
                if (shopImgInputStream != null && fileName!=null && !"".equals(fileName)) {
                    Shop tempShop = shopDao.queryByShopId(shop.getShopId());
                    if (tempShop.getShopImg() != null) {
                        ImageUtil.deleteFileOrPath(tempShop.getShopImg());
                    }
                    addShopImg(shop, 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 RuntimeException("modifyShop error: "
                        + e.getMessage());
            }
        }
    }

 

Controller層的實現

ShopManagementController中加入getShopById和modifyShop

@RequestMapping(value = "/getshopbyid",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getShopById(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        Long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        if(shopId>-1){
            try {
                //獲取店鋪信息
                Shop shop = shopService.getByShopId(shopId);
                //獲取區域列表
                List<Area> areaList = areaService.getAreaList();
                modelMap.put("shop",shop);
                modelMap.put("areaList",areaList);
                modelMap.put("success",true);
            } catch (Exception e) {
                modelMap.put("success",false);
                modelMap.put("errMsg",e.toString());
            }
        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","empty shopId");
        }
        return modelMap;
    }
@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> modifyShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //驗證碼
        if(!CodeUtil.checkVerifyCode(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 {
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        //接受圖片信息
        CommonsMultipartFile shopImg =null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if(commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest =
                    (MultipartHttpServletRequest)request;
            shopImg =
                    (CommonsMultipartFile)multipartHttpServletRequest.getFile("shopImg");

        }
        //2.修改店鋪信息
        if(shop!=null&&shop.getShopId()!=null){
            ShopExecution se = null;
            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());
                e.printStackTrace();
            }

            return modelMap;
        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","請輸入店鋪id");
            return modelMap;
        }

    }

修改/registershop添加session將用戶可以操作的店鋪列表添加到session

 @RequestMapping(value = "/registershop", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> listShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        //驗證碼
        if(!CodeUtil.checkVerifyCode(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 {
            shop = mapper.readValue(shopStr, Shop.class);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        //接受圖片信息
        CommonsMultipartFile shopImg =null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if(commonsMultipartResolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest =
                    (MultipartHttpServletRequest)request;
            shopImg =
                    (CommonsMultipartFile)multipartHttpServletRequest.getFile("shopImg");

        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","上傳圖片不能爲空");
            return modelMap;
        }
        //2.註冊店鋪
        if(shop!=null&&shopImg!=null){
            PersonInfo owner = (PersonInfo)request.getSession().getAttribute(
                    "user");
            shop.setOwner(owner);
            ShopExecution se = null;
            try {
                se = shopService.addShop(shop,
                        shopImg.getInputStream(),shopImg.getOriginalFilename());
                if(se.getState()== ShopStateEnum.CHECK.getState()){
                    modelMap.put("success",true);
                    //該用戶可以操作的店鋪列表
                    List<Shop> shopList =
                            (List<Shop>)request.getSession().getAttribute(
                                    "shopList");
                    if(shopList==null||shopList.size()==0){
                        shopList =new ArrayList<Shop>();
                    }
                    shopList.add(se.getShop());
                    request.getSession().setAttribute("shopList",shopList);
                }else {
                    modelMap.put("success",false);
                    modelMap.put("errMsg",se.getStateInfo());
                }
            } catch (IOException e) {
                modelMap.put("success",false);
                modelMap.put("errMsg",e.getMessage());
                e.printStackTrace();
            }

            return modelMap;
        }else {
            modelMap.put("success",false);
            modelMap.put("errMsg","請輸入店鋪信息");
            return modelMap;
        }

    }

店鋪信息編輯之前端實現

commonutil.js中加入以下代碼獲取shopId

function getQueryString(name){
    var reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null){
        return decodeURIComponent(r[2]);
    }
    return '';
}
$(function () {
    var shopId = getQueryString('shopId');
    var isEdit = shopId?true:false;

    var initUrl='/shopadmin/getshopinitinfo';
    //註冊店鋪
    var regidterShopUrl ='/shopadmin/registershop';
    //根據shopId獲取用戶信息
    var shopInfoUrl= "/shopadmin/getshopbyid?shopId="+shopId;
    var editShopUrl = '/shopadmin/modifyshop';

    //如果傳入shopId則調用getShopInfo(shopId)獲取店鋪信息以及區域列表
    if(!isEdit){
        getShopInitInfo();
    }else {
        getShopInfo(shopId);
    }

    function getShopInfo(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 option[data-id='"+shop.area.areaId+"]").attr("selected","selected");

            }
        });
    }
    function getShopInitInfo() {
        $.getJSON(initUrl,function (data) {
            if(data.success){
                var tempHtml="";
                //獲取區域信息
                var tempAreaHtml="";
                //後臺獲取的店鋪分類列表,遍歷
                data.shopCategoryList.map(function (item,index) {
                    tempHtml+='<option data-id="'+item.shopCategoryId+'">'+item.shopCategoryName+'</option>'
                });
                //區域信息
                data.areaList.map(function (item,index) {
                    tempAreaHtml+='<option data-id="'+item.areaId+'">'+item.areaName+'</option>';
                });
                $('#shop-category').html(tempHtml);
                $('#area').html(tempAreaHtml);

            }
        });

    }
    //點擊提交後的響應
    $('#submit').click(function () {
        var shop ={};
        if(isEdit){
            shop.shopId=shopId;
        }
        //從控件中獲取信息
        shop.shopName=$('#shop-name').val();
        shop.shopAddr=$('#shop-addr').val();
        shop.phone=$('#shop-phone').val();
        shop.shopDesc=$('#shop-desc').val();
        //獲取列表中的數據
        shop.shopCategory={
            shopCategoryId:$('#shop-category').find('option').not(function(){
                return !this.selected;
            }).data('id')
        };
        shop.area = {
            areaId:$('#area').find('option').not(function () {
                return !this.selected;
            }).data('id')
        };
        var shopImg =$('#shop-img')[0].files[0];
        var formData = new FormData();
        formData.append('shopImg',shopImg);
        formData.append('shopStr',JSON.stringify(shop));
        var verifyCodeActual=$('#j_captcha').val();
        if(!verifyCodeActual){
            $.toast('請輸入驗證碼!');
            return;
        }
        formData.append('verifyCodeActual',verifyCodeActual);
        $.ajax({
            url:editShopUrl,
            type:'POST',
            data:formData,
            contentType:false,
            processData:false,
            cache:false,
            success:function (data) {
                if(data.success){
                    $.toast('提交成功');
                }else{
                    $.toast('提交失敗'+data.errMsg);
                }
                $('#captcha_img').click();
            }
        });
    });
})

店鋪列表展示Dao的實現

在ShopDao插入

    /**
     * 分頁查詢店鋪,可輸入的條件有,店鋪名(模糊)查詢,店鋪狀態,店鋪類別,區域id,owner
     * @param shopCondition
     * @param roeIndex 從第幾行開始取數據
     * @param pageSize 返回的條數
     * @return
     */
    List<Shop> queryShopList(@Param("shopCondition")Shop shopCondition,
                             @Param("rowIndex")int roeIndex,
                             @Param("pageSize")int pageSize);

    /**
     * 返回queryShopList總數
     * @param shopCondition
     * @return
     */
    int queryShopCount(@Param("shopCondition")Shop shopCondition);

ShopDao.xml

<resultMap id="shopMap" type="com.imooc.o2o.entity.Shop">
        <id column="shop_id" property="shopId" />
        <result column="owner_id" property="ownerId" />
        <result column="shop_category_id" property="shopCategoryId" />
        <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="longitude" property="longitude" />
        <result column="latitude" property="latitude" />
        <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="queryShopList" resultMap="shopMap">
        SELECT
        s.shop_id,
        s.shop_name,
        s.shop_desc,
        s.shop_addr,
        s.phone,
        s.shop_img,
        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.area_id =
                #{shopCondition.area.areaId}
            </if>
            <!-- 寫like語句的時候 一般都會寫成 like '% %' 在mybatis裏面寫就是應該是 like '%${name} %' 而不是
    '%#{name} %' ${name} 是不帶單引號的,而#{name} 是帶單引號的 -->
            <if test="shopCondition.shopName!=null">
                and s.shop_name like '%${shopCondition.shopName}%'
            </if>
            <if test="shopCondition.enableStatus!=null">
                and s.enable_status = #{shopCondition.enableStatus}
            </if>
            <if test="shopCondition.owner!=null and shopCondition.owner.userId!=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.area_id =
                #{shopCondition.area.areaId}
            </if>
            <!-- 寫like語句的時候 一般都會寫成 like '% %' 在mybatis裏面寫就是應該是 like '%${name} %' 而不是
    '%#{name} %' ${name} 是不帶單引號的,而#{name} 是帶單引號的 -->
            <if test="shopCondition.shopName!=null">
                and s.shop_name like '%${shopCondition.shopName}%'
            </if>
            <if test="shopCondition.enableStatus!=null">
                and s.enable_status = #{shopCondition.enableStatus}
            </if>
            <if test="shopCondition.owner!=null and shopCondition.owner.userId!=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>

測試

 @Test
    public void testQueryShopListAndCount(){
        Shop shopCondition = new Shop();
        PersonInfo owner = new PersonInfo();
        owner.setUserId(1L);
        shopCondition.setOwner(owner);
        List<Shop> shopList =shopDao.queryShopList(shopCondition,0,5);
        int count= shopDao.queryShopCount(shopCondition);
        System.out.println("店鋪列表的大小"+shopList.size());
        System.out.println("店鋪的大小:"+count);
        ShopCategory sc =new ShopCategory();
        sc.setShopCategoryId(3L);
        shopCondition.setShopCategory(sc);
        shopList =shopDao.queryShopList(shopCondition,0,2);
        count =shopDao.queryShopCount(shopCondition);
        System.out.println(shopList);
        System.out.println(count);
    }

店鋪列表展示之Serive層的實現

ShopService中插入

    /**
     * 根據shopCondition分頁返回相應店鋪列表
     * @param shopCondition
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public ShopExecution getShopList(Shop shopCondition,int pageIndex,
                                     int pageSize);

在util新建PageCalculator

package com.imooc.o2o.util;

public class PageCalculator {
    public static int calculateRowIndex(int pageIndex,int pageSize){
        return (pageIndex>0)?(pageIndex-1)*pageSize:0;
    }
}

shopServiceImpl中插入

@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;
    }

測試

    @Test
    public void testGetShopList(){
        Shop shopCondition = new Shop();
        ShopCategory sc = new ShopCategory();
        sc.setShopCategoryId(1L);
        shopCondition.setShopCategory(sc);
        ShopExecution se = shopService.getShopList(shopCondition,3,5);
        System.out.println("店鋪列表數爲"+se.getShopList().size());
        System.out.println("店鋪總數爲"+se.getCount());
    }

店鋪列表展示之Contoller層的實現

在ShopManagementController.java插入以下代碼,根據用戶信息獲取店鋪列表

@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");
        request.getSession().setAttribute("user",user);
         user =(PersonInfo)request.getSession().getAttribute("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;
    }

在ShopManagementController.java插入以下代碼管理session相關操作 

 @RequestMapping(value = "/getshopmanagementinfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> getShopManagementInfo(HttpServletRequest request){
        //管理session相關的操作
        Map<String,Object> modelMap = new HashMap<String,Object>();
        //獲取店鋪id
        long shopId = HttpServletRequestUtil.getLong(request,"shopId");
        if(shopId<=0){
            //如果前端沒有傳id的話就從seesion中獲取
            Object currentShopObj = request.getSession().getAttribute(
                    "currentShop");
            if(currentShopObj==null){
                //重定向 沒登錄就直接到/shoplist店鋪列表中
                modelMap.put("redirect",true);
                modelMap.put("url","/shop/shoplist");
            }else {
                Shop currentShop= (Shop)currentShopObj;
                modelMap.put("redirect",false);
                modelMap.put("shopId",currentShop.getShopId());
            }
        }else {
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop",currentShop);
            modelMap.put("redirect",false);
        }
        return modelMap;
    }

店鋪列表展示前端開發

shoplist.html

<!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>
            <a class="pull-right" href="/shopadmin/shopoperation">增加店鋪</a>
        </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>

shoplist.css

.row-shop {
    border: 1px solid #999;
    padding: .5rem;
    border-bottom: none;
}
.row-shop:last-child {
    border-bottom: 1px solid #999;
}
.shop-name {
    white-space: nowrap;
    overflow-x: scroll;
}
.shop-wrap a {

}

shoplist.js

$(function () {
    getlist();
    function getlist(e) {
        $.ajax({
            url:"/shopadmin/getshoplist",
            type:"get",
            dateType:"json",
            success:function (date) {
                if(date.success){
                    handleList(date.shopList);
                    handleUser(date.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 shopStatus(status) {
        if(status==0){
            return '審覈中';
        }else if(status ==-1){
            return '店鋪非法';
        }else if(status==1){
            return '審覈通過';
        }
    }

    function goShop(status,id) {
        if(status==1){
            return'<a href="/shop/shopmanage?shopId='+id+'">進入</a>';
        }else {
            return '';
        }
    }
});

shopAdminController

package com.imooc.o2o.web.shopadmin;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "shopadmin",method = {RequestMethod.GET})
public class ShopAdminController {
    @RequestMapping(value = "/shopoperation")
    public String shopOperation(){
        return "shop/shopoperation";
    }

    @RequestMapping(value = "/shoplist")
    public String shopList(){
        return "shop/shoplist";
    }
}

店鋪管理頁面的前端開發

shopmanagement.html導入css文件和commonutil.js和shopmanage.js文件

<!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="/shop/shopedit" class="button button-big button-fill">商鋪信息</a>
            </div>
            <div class="col-50 mb">
                <a href="/shop/productmanage" class="button button-big button-fill">商品管理</a>
            </div>
            <div class="col-50 mb">
                <a href="/shop/productcategorymanage" class="button button-big button-fill">類別管理</a>
            </div>
            <div class="col-100 mb">
                <a href="/shop/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>
<script type='text/javascript'
        src='../resources/js/common/commonutil.js' charset='utf-8'></script>
</body>
</html>

shopmanage.js

$(function () {
    var shopId = getQueryString('shopId');
    var shopInfoUrl="/shopadmin/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('href','/shopadmin/shopoperation?shopId='+shopId);
        }
    });
});

commonutil.js 

function changeVerifyCode(img) {
    img.src="../Kaptcha?"+Math.floor(Math.random()*100);
}

function getQueryString(name){
    var reg = new RegExp("(^|&)"+name+"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null){
        return decodeURIComponent(r[2]);
    }
    return '';
}

shopadminController.java加入

    @RequestMapping(value = "/shopmanagement")
    public String shopManagement(){
        return "shop/shopmanagement";
    }

進入/shopmanagement會自動重定向

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