zoukankan      html  css  js  c++  java
  • 商铺项目(店铺编辑和列表功能)

    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,然后点击进入,点击商铺信息,看能不能跑通过。

  • 相关阅读:
    053705
    053704
    053703
    053702
    053701
    053700
    053699
    053698
    053697
    HDU 3746 Cyclic Nacklace
  • 原文地址:https://www.cnblogs.com/XJJD/p/7695705.html
Copyright © 2011-2022 走看看