商鋪項目(店鋪編輯和列表功能)


Dao層實現:

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.ouyan.o2o.dao.ShopDao">
    <resultMap id="shopMap" type="com.ouyan.o2o.entity.Shop">
        <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.ouyan.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.ouyan.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.ouyan.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.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
        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.ouyan.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>

ShopDaoTest:

package com.ouyan.o2o.dao;

import static org.junit.Assert.assertEquals;

import java.util.Date;

import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.ouyan.o2o.BaseTest;
import com.ouyan.o2o.entity.Area;
import com.ouyan.o2o.entity.PersonInfo;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.entity.ShopCategory;

public class ShopDaoTest extends BaseTest{
    @Autowired
    private ShopDao shopDao;
    @Test
    public void testQueryByshopId(){
        Shop shop = shopDao.queryByShopId(62L);
        System.out.println(shop.getShopId());
        System.out.println(shop.getShopName());
    }
    @Test
    @Ignore
    public void testInsertShop(){
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory = new ShopCategory();
        owner.setUserId(1L);
        area.setAreaId(2L);
        shopCategory.setShopCategoryId(33L);
        shop.setOwner(owner);
        shop.setArea(area);
        shop.setShopCategory(shopCategory);
        shop.setShopName("測試的店鋪");
        shop.setShopDesc("test");
        shop.setShopAddr("test");
        shop.setPhone("test");
        shop.setShopImg("test");
        shop.setCreateTime(new Date());
        shop.setEnableStatus(1);
        shop.setAdvice("審核中");
        int effectedNum = shopDao.insertShop(shop);
        assertEquals(1,effectedNum);
    }
    @Test
    @Ignore
    public void testUpdateShop(){
        Shop shop = new Shop();
        shop.setShopId(30L);
        shop.setShopDesc("測試描述");
        shop.setShopAddr("測試地址");
        shop.setLastEditTime(new Date());
        int effectedNum = shopDao.updateShop(shop);
        assertEquals(1,effectedNum);
    }
}

ShopDao:

package com.ouyan.o2o.dao;

import com.ouyan.o2o.entity.Shop;

public interface ShopDao {
    /**
     * 通過shopId查詢項目
     */
    Shop queryByShopId(Long shopId);
    /**
     * 新增店鋪
     */
    int insertShop(Shop shop);
    
    /**
     * 更新店鋪信息
     */
    int updateShop(Shop shop);
}

然后測試。

Service層實現:

ShopServiceImpl:

package com.ouyan.o2o.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ouyan.o2o.dao.ShopDao;
import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.enums.ShopStateEnum;
import com.ouyan.o2o.exceptions.ShopOperationException;
import com.ouyan.o2o.service.ShopService;
import com.ouyan.o2o.util.PathUtil;
import com.ouyan.o2o.util.imageUtil;
@Service
public class ShopServiceImpl implements ShopService{
    @Autowired
    private ShopDao shopDao;
    
    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, InputStream shopImgInputStream,String fileName) {
        //空值判斷
        if(shop==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }
        try {
            //給店鋪信息賦值初始值
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            //添加店鋪信息
            int effectedNum = shopDao.insertShop(shop);
            if(effectedNum<=0){
                throw new ShopOperationException("店鋪創建失敗");
            }else{
                if(shopImgInputStream!=null){
                    //存儲圖片
                    try {
                        addShopImg(shop,shopImgInputStream,fileName);
                    } catch (Exception e) {
                        throw new ShopOperationException("addShopImg error:"+e.getMessage());
                    }
                    effectedNum = shopDao.updateShop(shop);
                    if(effectedNum<=0){
                        throw new ShopOperationException("更新圖片地址失敗");
                    }
                }
            }
        } catch (Exception e) {
            throw new ShopOperationException("addShop error: "+ e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHECK,shop);
    }

    private void addShopImg(Shop shop, InputStream shopImgInputStream,String fileName) throws ShopOperationException, IOException {
        //獲取shop圖片的相對路徑
        String dest = PathUtil.getShopImagePath(shop.getShopId());
        String shopImgAddr = imageUtil.generateThumbnail(shopImgInputStream,fileName,dest);
        shop.setShopImg(shopImgAddr);
    }

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

    @Override
    public ShopExecution modifyShop(Shop shop, InputStream shopImgInputStream, String fileName)
            throws ShopOperationException {
        if(shop==null||shop.getShopId()==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }else{
            //判斷是否需要處理圖片
            try{
            if(shopImgInputStream!=null&&fileName!=null&&!"".equals(fileName)){
                Shop tempShop = shopDao.queryByShopId(shop.getShopId());
                if(tempShop.getShopImg()!=null){
                    imageUtil.deleteFileOrPath(tempShop.getShopImg());
                }
                try {
                    addShopImg(shop,shopImgInputStream,fileName);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //更新店鋪信息
            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());
            }
        }
    }
}

ImageUtil:

package com.ouyan.o2o.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

public class imageUtil {
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random r = new Random();
    private static Logger logger = LoggerFactory.getLogger(imageUtil.class);

    /**
     * 將CommonsMultipartFile轉換成file
     * 
     * @param cFile
     * @return
     */
    public static File transferCommonsMultipartFileToFile(CommonsMultipartFile cFile) {
        File newFile = new File(cFile.getOriginalFilename());
        try {
            cFile.transferTo(newFile);
        } catch (IllegalStateException e) {
            logger.error(e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error(e.toString());
            e.printStackTrace();
        }
        return newFile;
    }

    /**
     * 處理縮略圖並返回新生成圖片的相對值路徑
     * 
     * @param thumbnail
     * @param targetAddr
     * @return
     * @throws IOException
     */
    public static String generateThumbnail(InputStream thumbnailInputStream, String fileName, String targetAddr) throws IOException
             {
        String realFileName = getRandomFileName();
        String extension = getFileExtesion(fileName);
        makeDirPath(targetAddr);
        String relativeAddr = targetAddr + realFileName + extension;
        logger.error("current relativeAddr is:" + relativeAddr);
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        logger.debug("current complete addr is :" + PathUtil.getImgBasePath() + relativeAddr);
        Thumbnails.of(thumbnailInputStream).size(200, 200)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f)
                .outputQuality(0.8).toFile(dest);
        return relativeAddr;
    }

    /**
     * 創建目標路徑涉及的目錄
     * 
     * @param targetAddr
     */
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = PathUtil.getImgBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }

    /**
     * 獲取輸入文件的擴展名
     * 
     * @param thumbnail
     * @return
     */
    private static String getFileExtesion(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成隨機文件名,當前年月是小時分鍾秒鍾+五位隨機數
     * 
     * @return
     */
    public static String getRandomFileName() {
        // 獲取隨機的五位數
        int rannum = r.nextInt(89999) + 10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return nowTimeStr + rannum;
    }

    public static void main(String[] args) throws IOException {
        Thumbnails.of(new File("d:\\timg.jpg")).size(2000, 2000)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")), 0.25f)
                .outputQuality(0.8f).toFile("d:\\timgnew.jpg");
    }

    /**
     * 刪除圖片或者目錄下的所有圖片
     * 
     * @param storePath
     */
    public static void deleteFileOrPath(String storePath) {
        File fileOrPath = new File(PathUtil.getImgBasePath() + storePath);
        if (fileOrPath.exists()) {
            if (fileOrPath.isDirectory()) {
                File files[] = fileOrPath.listFiles();
                for (int i = 0; i < files.length; i++) {
                    files[i].delete();
                }
            }
            fileOrPath.delete();
        }
    }
}

ShopService:

package com.ouyan.o2o.service;

import java.io.InputStream;

import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.exceptions.ShopOperationException;

public interface ShopService {
    /**
     * 根據店鋪ID查詢店鋪
     * 
     * @param shopId
     * @return
     */
    Shop getByShopId(long shopId);

    /**
     * 修改店鋪
     * 
     * @param shop
     * @param inputStream
     * @param fileName
     * @return
     * @throws ShopOperationException
     */
    ShopExecution modifyShop(Shop shop, InputStream shopImgInputStream, String fileName) throws ShopOperationException;

    /**
     * 添加店鋪
     * 
     * @param shop
     * @param shopImgInputStream
     * @param fileName
     * @return
     */
    ShopExecution addShop(Shop shop, InputStream shopImgInputStream, String fileName) throws ShopOperationException;
}

ShopServiceTest:

package com.ouyan.o2o.service;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ouyan.o2o.BaseTest;
import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Area;
import com.ouyan.o2o.entity.PersonInfo;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.entity.ShopCategory;
import com.ouyan.o2o.enums.ShopStateEnum;

@Service
public class ShopServiceTest extends BaseTest {
    @Autowired
    private ShopService shopService;

    @Test
    public void testModifyShop() throws FileNotFoundException {
        Shop shop = new Shop();
        shop.setShopId(62L);
        shop.setShopName("修改后的店鋪名稱");
        File shopImg = new File("d:/haha.jpg");
        InputStream is = new FileInputStream(shopImg);
        ShopExecution shopExecution = shopService.modifyShop(shop, is, "haha1.jpg");
        System.out.println("新地址是: "+shopExecution.getShop().getShopImg());
    }

    @Test
    public void testAddShop() throws FileNotFoundException {
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory = new ShopCategory();
        owner.setUserId(1L);
        area.setAreaId(2L);
        shopCategory.setShopCategoryId(33L);
        shop.setOwner(owner);
        shop.setArea(area);
        shop.setShopCategory(shopCategory);
        shop.setShopName("測試的店鋪3");
        shop.setShopDesc("test3");
        shop.setShopAddr("test3");
        shop.setPhone("test3");
        shop.setCreateTime(new Date());
        shop.setEnableStatus(ShopStateEnum.CHECK.getState());
        shop.setAdvice("審核中");
        File shopImg = new File("d:/timg.jpg");
        InputStream is = new FileInputStream(shopImg);
        ShopExecution se = shopService.addShop(shop, is, shopImg.getName());
        assertEquals(ShopStateEnum.CHECK.getState(), se.getState());
    }
}

然后測試。。。這時候發現數據源還是服務器上的,測了很久沒成功才發現。。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.slave.url=jdbc:mysql://localhost:3306/o2o?useUnicode=true&characterEncoding=utf8
jdbc.master.url=jdbc:mysql://localhost:3306/o2o?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=admin

然后發現一個巨坑,com.ouyan.o2o.dao.split放錯位置了。。難怪老是注入失敗。

測試一下吧:localhost:8080/o2o/shopadmin/getshopbyid?shopId=62

shopoperation.js

/**
 * 
 */
$(function(){
    var shopId=getQueryString('shopId');
    var isEdit=shopId?true:false;
    var initUrl='/o2o/shopadmin/getshopinitinfo';
    var registerShopUrl='/o2o/shopadmin/registershop';
    var shopInfoUrl="/o2o/shopadmin/getshopbyid?shopId="+shopId;
    var editShopUrl="/o2o/shopadmin/modifyshop";
    if(!isEdit){
        getShopInitInfo();
    }else{
        getShopInfo();
    }
    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+'</oprion>';
                });
                $('#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:(isEdit?editShopUrl:registerShopUrl),
                type:'POST',
                data:formData,
                contentType:false,
                processData:false,
                cache:false,
                success:function(data){
                    if(data.success){
                        $.toast('提交成功!');
                    }else{
                        $.toast('提交失敗!'+data.errMsg);
                    }
                    $('captcha-img').click();
                }
            });
        });
    
})

common.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 '';
}

在前端和Controller打幾個斷點調試,后端在:

registershop和modifyshop

 

下面我們看下店鋪列表的Dao層實現:

package com.ouyan.o2o.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.ouyan.o2o.entity.Shop;

public interface ShopDao {
    /**
     * 分頁查詢店鋪,可輸入的條件有:店鋪名(模糊),店鋪狀態,店鋪類別,區域ID,owner
     * @param shopCondition
     * @param rowIndex從第幾行開始取數據
     * @param pageSize返回的條數
     * @return
     */
    List<Shop> queryShopList(@Param("shopCondition") Shop shopCondition,@Param("rowIndex") int rowIndex,@Param("pageSize") int pageSize);
    
    /**
     * 返回queryShopList總數
     * @param shopCondition
     * @return
     */
    int queryShopCount(@Param("shopCondition") Shop shopCondition);
    /**
     * 通過shopId查詢店鋪
     */
    Shop queryByShopId(Long shopId);
    /**
     * 新增店鋪
     */
    int insertShop(Shop shop);
    
    /**
     * 更新店鋪信息
     */
    int updateShop(Shop shop);
}

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.ouyan.o2o.dao.ShopDao">
    <resultMap id="shopMap" type="com.ouyan.o2o.entity.Shop">
        <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.ouyan.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.ouyan.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.ouyan.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.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.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.enable_Status=#{shopCondition.enableStatus}
            </if>
            <if test="shopCondition.owner!=null and shopCondition.owner.userId !=null">
                and s.owner_id=#{shopCondition.owner.userId}
            </if>
            AND
            a.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>
            <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
            a.area_id=a.area_id
            AND
            s.shop_category_id=sc.shop_category_id
        </where>
    </select>

    <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.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
        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.ouyan.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>
package com.ouyan.o2o.dao;

import static org.junit.Assert.assertEquals;

import java.util.Date;
import java.util.List;

import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.ouyan.o2o.BaseTest;
import com.ouyan.o2o.entity.Area;
import com.ouyan.o2o.entity.PersonInfo;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.entity.ShopCategory;

public class ShopDaoTest extends BaseTest {
    @Autowired
    private ShopDao shopDao;

    @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);
        System.out.println(shopList.size());
        int i = shopDao.queryShopCount(shopCondition);
        System.out.println(i);
    }
    
    @Test
    @Ignore
    public void testQueryByshopId() {
        Shop shop = shopDao.queryByShopId(62L);
        System.out.println(shop.getShopId());
        System.out.println(shop.getShopName());
    }

    @Test
    @Ignore
    public void testInsertShop() {
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory = new ShopCategory();
        owner.setUserId(1L);
        area.setAreaId(2L);
        shopCategory.setShopCategoryId(33L);
        shop.setOwner(owner);
        shop.setArea(area);
        shop.setShopCategory(shopCategory);
        shop.setShopName("測試的店鋪");
        shop.setShopDesc("test");
        shop.setShopAddr("test");
        shop.setPhone("test");
        shop.setShopImg("test");
        shop.setCreateTime(new Date());
        shop.setEnableStatus(1);
        shop.setAdvice("審核中");
        int effectedNum = shopDao.insertShop(shop);
        assertEquals(1, effectedNum);
    }

    @Test
    @Ignore
    public void testUpdateShop() {
        Shop shop = new Shop();
        shop.setShopId(30L);
        shop.setShopDesc("測試描述");
        shop.setShopAddr("測試地址");
        shop.setLastEditTime(new Date());
        int effectedNum = shopDao.updateShop(shop);
        assertEquals(1, effectedNum);
    }
}

測試一下,通過。

下面我們看下店鋪列表的Service層實現:

package com.ouyan.o2o.service;

import java.io.InputStream;

import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.exceptions.ShopOperationException;

public interface ShopService {
    /**
     * 根據shopCondition分頁返回相應店鋪列表
     * @param shopCondition
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public ShopExecution getShopList(Shop shopCondition,int pageIndex,int pageSize);
    
    /**
     * 根據店鋪ID查詢店鋪
     * 
     * @param shopId
     * @return
     */
    Shop getByShopId(long shopId);

    /**
     * 修改店鋪
     * 
     * @param shop
     * @param inputStream
     * @param fileName
     * @return
     * @throws ShopOperationException
     */
    ShopExecution modifyShop(Shop shop, InputStream shopImgInputStream, String fileName) throws ShopOperationException;

    /**
     * 添加店鋪
     * 
     * @param shop
     * @param shopImgInputStream
     * @param fileName
     * @return
     */
    ShopExecution addShop(Shop shop, InputStream shopImgInputStream, String fileName) throws ShopOperationException;
}
package com.ouyan.o2o.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ouyan.o2o.dao.ShopDao;
import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.enums.ShopStateEnum;
import com.ouyan.o2o.exceptions.ShopOperationException;
import com.ouyan.o2o.service.ShopService;
import com.ouyan.o2o.util.PageCalculator;
import com.ouyan.o2o.util.PathUtil;
import com.ouyan.o2o.util.imageUtil;
@Service
public class ShopServiceImpl implements ShopService{
    @Autowired
    private ShopDao shopDao;
    
    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, InputStream shopImgInputStream,String fileName) {
        //空值判斷
        if(shop==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }
        try {
            //給店鋪信息賦值初始值
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            //添加店鋪信息
            int effectedNum = shopDao.insertShop(shop);
            if(effectedNum<=0){
                throw new ShopOperationException("店鋪創建失敗");
            }else{
                if(shopImgInputStream!=null){
                    //存儲圖片
                    try {
                        addShopImg(shop,shopImgInputStream,fileName);
                    } catch (Exception e) {
                        throw new ShopOperationException("addShopImg error:"+e.getMessage());
                    }
                    effectedNum = shopDao.updateShop(shop);
                    if(effectedNum<=0){
                        throw new ShopOperationException("更新圖片地址失敗");
                    }
                }
            }
        } catch (Exception e) {
            throw new ShopOperationException("addShop error: "+ e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHECK,shop);
    }

    private void addShopImg(Shop shop, InputStream shopImgInputStream,String fileName) throws ShopOperationException, IOException {
        //獲取shop圖片的相對路徑
        String dest = PathUtil.getShopImagePath(shop.getShopId());
        String shopImgAddr = imageUtil.generateThumbnail(shopImgInputStream,fileName,dest);
        shop.setShopImg(shopImgAddr);
    }

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

    @Override
    public ShopExecution modifyShop(Shop shop, InputStream shopImgInputStream, String fileName)
            throws ShopOperationException {
        if(shop==null||shop.getShopId()==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }else{
            //判斷是否需要處理圖片
            try{
            if(shopImgInputStream!=null&&fileName!=null&&!"".equals(fileName)){
                Shop tempShop = shopDao.queryByShopId(shop.getShopId());
                if(tempShop.getShopImg()!=null){
                    imageUtil.deleteFileOrPath(tempShop.getShopImg());
                }
                try {
                    addShopImg(shop,shopImgInputStream,fileName);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //更新店鋪信息
            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());
            }
        }
    }

    @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;
    }
}
package com.ouyan.o2o.util;

public class PageCalculator {
    public static int calculateRowIndex(int pageIndex,int pageSize){
        return (pageIndex >0)?(pageIndex-1)*pageSize:0;
    }
}
package com.ouyan.o2o.service;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ouyan.o2o.BaseTest;
import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Area;
import com.ouyan.o2o.entity.PersonInfo;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.entity.ShopCategory;
import com.ouyan.o2o.enums.ShopStateEnum;

@Service
public class ShopServiceTest extends BaseTest {
    @Autowired
    private ShopService shopService;
    
    @Test
    public void testGetShopList(){
        Shop shopCondition = new Shop();
        ShopCategory sc = new ShopCategory();
        sc.setShopCategoryId(33L);
        shopCondition.setShopCategory(sc);
        ShopExecution se=shopService.getShopList(shopCondition, 1, 2);
        System.out.println(se.getShopList().size());
        System.out.println(se.getCount());
    }
    
    @Test
    public void testModifyShop() throws FileNotFoundException {
        Shop shop = new Shop();
        shop.setShopId(62L);
        shop.setShopName("修改后的店鋪名稱");
        File shopImg = new File("d:/haha.jpg");
        InputStream is = new FileInputStream(shopImg);
        ShopExecution shopExecution = shopService.modifyShop(shop, is, "haha1.jpg");
        System.out.println("新地址是: "+shopExecution.getShop().getShopImg());
    }

    @Test
    public void testAddShop() throws FileNotFoundException {
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory = new ShopCategory();
        owner.setUserId(1L);
        area.setAreaId(2L);
        shopCategory.setShopCategoryId(33L);
        shop.setOwner(owner);
        shop.setArea(area);
        shop.setShopCategory(shopCategory);
        shop.setShopName("測試的店鋪3");
        shop.setShopDesc("test3");
        shop.setShopAddr("test3");
        shop.setPhone("test3");
        shop.setCreateTime(new Date());
        shop.setEnableStatus(ShopStateEnum.CHECK.getState());
        shop.setAdvice("審核中");
        File shopImg = new File("d:/timg.jpg");
        InputStream is = new FileInputStream(shopImg);
        ShopExecution se = shopService.addShop(shop, is, shopImg.getName());
        assertEquals(ShopStateEnum.CHECK.getState(), se.getState());
    }
}

然后測試該方法。

下面我們看下店鋪列表的Controller層實現:

package com.ouyan.o2o.web.shopadmin;

import java.io.IOException;
import java.util.ArrayList;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Area;
import com.ouyan.o2o.entity.PersonInfo;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.entity.ShopCategory;
import com.ouyan.o2o.enums.ShopStateEnum;
import com.ouyan.o2o.exceptions.ShopOperationException;
import com.ouyan.o2o.service.AreaService;
import com.ouyan.o2o.service.ShopCategoryService;
import com.ouyan.o2o.service.ShopService;
import com.ouyan.o2o.util.CodeUtil;
import com.ouyan.o2o.util.HttpServletRequestUtil;

@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryService ShopCategoryService;
    @Autowired
    private AreaService areaService;

    @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");
        if(shopId<=0){
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            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());
            }
        }else{
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop", currentShop);
            modelMap.put("redirect", false);
        }
        return modelMap;
    }
    
    
    @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("測試");
        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;
    }
    
    @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 = "/getshopinitinfo", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getShopInitInfo() {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
        List<Area> areaList = new ArrayList<Area>();
        try {
            shopCategoryList = ShopCategoryService.getShopCategoryList(new ShopCategory());
            areaList = areaService.getAreaList();
            modelMap.put("shopCategoryList", shopCategoryList);
            modelMap.put("areaList", areaList);
            modelMap.put("success", true);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        return modelMap;

    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/registershop", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "輸入了錯誤的驗證碼");
            return modelMap;
        }
        // 接受並轉化相應參數
        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());
            return modelMap;
        }
        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;
        }
        // 注冊店鋪
        if (shop != null && shopImg != null) {
            PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
            shop.setOwner(owner);
            ShopExecution se;
            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.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 (ShopOperationException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
            return modelMap;
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "請輸入店鋪信息");
            return modelMap;
        }
    }

    @RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
    @ResponseBody
    public 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;
        }
        // 接受並轉化相應參數
        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());
            return modelMap;
        }
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }
        // 修改店鋪
        if (shop != null && shop.getShopId() != null) {
            ShopExecution se;
            try {
                if (shopImg == null) {
                    se = shopService.modifyShop(shop, null, shopImg.getOriginalFilename());
                } 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 (ShopOperationException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
            return modelMap;
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "請輸入店鋪id");
            return modelMap;
        }
    }
}

下面來看前端開發:
在shop目錄下新建一個javasciprt source folder:

$(function() {
    getlist();
    function getlist(e) {
        $.ajax({
            url : "/o2o/shopadmin/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/shopoperate?shopId='+ id +'">進入</a>';
        } else {
            return '';
        }
    }

    function shopStatus(status) {
        if (status == 0) {
            return '審核中';
        } else if (status == -1) {
            return '店鋪非法';
        } else {
            return '審核通過';
        }
    }
})

<!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="/o2o/shopadmin/shopoperate">增加店鋪</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-33">
                    <a href="/o2o/local/accountbind?usertype=2"
                        class="button button-big button-fill button-success">帳號綁定</a>
                </div>
                <div class="col-33">
                    <a href="#" id="log-out" usertype="2"
                        class="button button-big button-fill button-danger">退出系統</a>
                </div>
                <div class="col-33">
                    <a href="/o2o/local/changepsw?usertype=2"
                        class="button button-big button-fill button-success"
                        id="bindOrChange">修改密碼</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>
    <script type='text/javascript' src='../resources/js/local/logout.js'
        charset='utf-8'></script>        
</body>
</html>

 

.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 {

}

package com.ouyan.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="/shopoperate")
    public String shopOperation(){
        return "shop/shopoperation";
    }
    
    @RequestMapping(value="/shoplist")
    public String shopList(){
        return "shop/shoplist";
    }
}

這時候發現,因為是讀數據,肯定是在從庫中查詢的,但是我在主庫中執行了sql:mysql> update o2o.tb_shop set enable_status = '1' where shop_id='62'

但是然並卵,從庫中老是不生效,也就是說沒有同步過去,產生了延遲。

最后才發現,必須這樣寫,才能主從同步:

use o2o;
update o2o.tb_shop set enable_status = '1' where shop_id='62';

另外有一種方案是:

可以采用Redis技術, 新浪微博就大量使用了Redis技術。 區別於Memcached的是,redis會周期性的把更新的數據寫入磁盤或者把修改操作寫入追加的記錄文件,並且在此基礎上實現了主從同步。

然后發現一個問題,項目調試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/shopmanagement.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 id="shopInfo" href="/o2o/shopadmin/shopoperate"
                        class="button button-big button-fill">商鋪信息</a>
                </div>
                <div class="col-50 mb">
                    <a href="/o2o/shopadmin/productmanagement"
                        class="button button-big button-fill">商品管理</a>
                </div>
                <div class="col-50 mb">
                    <a href="/o2o/shopadmin/productcategorymanagement"
                        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/common/common.js' charset='utf-8'></script>
    <script type='text/javascript' src='../resources/js/shop/shopmanagement.js'
        charset='utf-8'></script>
</body>
</html>

 

$(function() {
    var shopId = getQueryString('shopId');
    var shopInfoUrl = '/o2o/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', '/o2o/shopadmin/shopoperate?shopId=' + shopId);
        }
    });
});
package com.ouyan.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="/shopoperate")
    public String shopOperation(){
        return "shop/shopoperation";
    }
    
    @RequestMapping(value="/shoplist")
    public String shopList(){
        return "shop/shoplist";
    }
    
    @RequestMapping(value="/shopmanagement")
    public String shopManagement(){
        return "shop/shopmanagement";
    }
}
package com.ouyan.o2o.web.shopadmin;

import java.io.IOException;
import java.util.ArrayList;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ouyan.o2o.dto.ShopExecution;
import com.ouyan.o2o.entity.Area;
import com.ouyan.o2o.entity.PersonInfo;
import com.ouyan.o2o.entity.Shop;
import com.ouyan.o2o.entity.ShopCategory;
import com.ouyan.o2o.enums.ShopStateEnum;
import com.ouyan.o2o.exceptions.ShopOperationException;
import com.ouyan.o2o.service.AreaService;
import com.ouyan.o2o.service.ShopCategoryService;
import com.ouyan.o2o.service.ShopService;
import com.ouyan.o2o.util.CodeUtil;
import com.ouyan.o2o.util.HttpServletRequestUtil;

@Controller
@RequestMapping("/shopadmin")
public class ShopManagementController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryService ShopCategoryService;
    @Autowired
    private AreaService areaService;

    @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");
        if(shopId<=0){
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if(currentShopObj==null){
                modelMap.put("redirect", true);
                modelMap.put("url", "/o2o/shopadmin/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;
    }
    
    
    @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("Poker");
        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;
    }
    
    @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 = "/getshopinitinfo", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getShopInitInfo() {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        List<ShopCategory> shopCategoryList = new ArrayList<ShopCategory>();
        List<Area> areaList = new ArrayList<Area>();
        try {
            shopCategoryList = ShopCategoryService.getShopCategoryList(new ShopCategory());
            areaList = areaService.getAreaList();
            modelMap.put("shopCategoryList", shopCategoryList);
            modelMap.put("areaList", areaList);
            modelMap.put("success", true);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        return modelMap;

    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/registershop", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> registerShop(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("success", false);
            modelMap.put("errMsg", "輸入了錯誤的驗證碼");
            return modelMap;
        }
        // 接受並轉化相應參數
        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());
            return modelMap;
        }
        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;
        }
        // 注冊店鋪
        if (shop != null && shopImg != null) {
            PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
            shop.setOwner(owner);
            ShopExecution se;
            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.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 (ShopOperationException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
            return modelMap;
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "請輸入店鋪信息");
            return modelMap;
        }
    }

    @RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
    @ResponseBody
    public 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;
        }
        // 接受並轉化相應參數
        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());
            return modelMap;
        }
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }
        // 修改店鋪
        if (shop != null && shop.getShopId() != null) {
            ShopExecution se;
            try {
                if (shopImg == null) {
                    se = shopService.modifyShop(shop, null, shopImg.getOriginalFilename());
                } 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 (ShopOperationException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
            return modelMap;
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "請輸入店鋪id");
            return modelMap;
        }
    }
}

$(function() {
    getlist();
    function getlist(e) {
        $.ajax({
            url : "/o2o/shopadmin/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/shopmanagement?shopId='+ id +'">進入</a>';
        } else {
            return '';
        }
    }

    function shopStatus(status) {
        if (status == 0) {
            return '審核中';
        } else if (status == -1) {
            return '店鋪非法';
        } else {
            return '審核通過';
        }
    }
})

訪問:http://localhost:8080/o2o/shopadmin/shopmanagement,然后點擊進入,點擊商鋪信息,看能不能跑通過。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM