从零开发校园商铺平台(SSM到SpringBoot)四.店铺注册功能模块


前尘往事,如烟似梦,想来缘浅,奈何情深,岁月如潮,沁漫沙滩。


4.1 Dao层之新增店铺

这里写图片描述

src/main/java/com.imooc.o2o.dao 目录下新建 ShopDao.java接口。

package com.imooc.o2o.dao;

import com.imooc.o2o.entity.Shop;

public interface ShopDao {

    /**
     * 新增店铺
     * @param shop
     * @return
     */
    int insertShop(Shop shop);
}

src/main/resources/mapper路径下创建ShopDao.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.imooc.o2o.dao.ShopDao">
    <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)
        VALUSE
        (#{owner.userId},#{area.areaId},#{shopCategory.shopCategoryId},#{shopName},
        #{shopDesc},#{shopAddr},#{phone},#{shopImg},#{priority},#{createTime},
        #{lastEditTime},#{enableStatus},#{advice})
    </insert>
</mapper>

数据库添加测试数据

insert into `o2o`.`tb_shop_category` ( `shop_category_name`, `shop_category_desc`, `shop_category_img`, `priority`) values ( '咖啡奶茶', '咖啡奶茶', 'test', '1')

insert into `o2o`.`tb_person_info` ( `name`, `profile_img`, `email`, `gender`, `enable_status`, `user_type`) values ( '测试', 'test', 'test', '1', '1', '2')

com.imooc.o2o.dao目录下创建ShopDaoTest.java进行单元测试

package com.imooc.o2o.dao;

import static org.junit.Assert.assertEquals;

import java.util.Date;

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

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

public class ShopDaoTest extends BaseTest{

    @Autowired
    private ShopDao shopDao;
    @Test
    public void testInsertShop() {
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory = new ShopCategory();
        owner.setUserId(1L);
        area.setAreaId(2);
        shopCategory.setShopCategoryId(1L);
        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);

    }
}

运行

这里写图片描述

这里写图片描述

4.2 Dao层之更新店铺

src/main/java/com.imooc.o2o.dao目录下ShopDao.java新增代码

/**
 * 更新店铺信息
 */
int updateShop(Shop shop);

src/main/resources/mapper目录下ShopDao.xml新增代码

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

src/test/java/com.imooc.o2o.dao目录下ShopDaoTest.java添加代码

@Test
    public void testUpdateShop() {
        Shop shop = new Shop();
        shop.setShopId(1L);
        shop.setShopDesc("测试描述");
        shop.setShopAddr("测试地址");
        int effectedNum = shopDao.updateShop(shop);
        assertEquals(1, effectedNum);   
    }

testInsertShop方法上面添加@Ignore标签,JUnit则不会触发testInsertShop方法了。

Run As执行测试。没发现错误就ok了。

4.3 Thumbnailator图片处理和封装Util

打开链接 http://www.mvnrepository.com/search?q=Thumbnailator

<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>

我们在之前的pom.xml配置中也配置过.

在src/main/java/com.imooc.o2o.util路径下新建ImageUtil.java类

在src/main/resources路径下放置一张图片

这里写图片描述

在/Users/mac/Downloads/luoto.png 存入另外一张图片。为此图片添加上面图片的水印。

package com.imooc.o2o.util;

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

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

public class ImageUtil {

    public static void main(String[] args) throws IOException {
        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        Thumbnails.of(new File("/Users/mac/Downloads/luoto.png")).size(200, 200)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/jingyu.png")), 0.25f)
                .outputQuality(0.8f).toFile("/Users/mac/Downloads/luotonew.png");
    }
}

运行main函数,我们发现在/Users/mac/Downloads路径下多出一张luotonew.png的水印图片。

这里写图片描述

src/main/java/com.imooc.o2o.util路径下创建PathUtil.java类

package com.imooc.o2o.util;

public class PathUtil {

    /*
     * 根据不同的操作系统,设置储存图片文件不同的根目录
     */
    private static String seperator = System.getProperty("file.separator");
    public static String getImgBasePath() {

        String os =System.getProperty("os.name");
        String basePath = "";
        if(os.toLowerCase().startsWith("win")) {
          basePath = "D:/projectdev/image/";    //根据自己的实际路径进行设置
        }else {
            basePath = "/home/o2o/image/";//根据自己的实际路径进行设置
        }
        basePath = basePath.replace("/", seperator);
        return basePath;
    }

    //根据不同的业务需求返回不同的子路径
    public static String getShopImagePath(long shopId) {
        String imagePath = "/upkoad/item/shop/"+ shopId + "/";
        return imagePath.replace("/", seperator);
    }
}

修改ImageUtil.java类

package com.imooc.o2o.util;

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

import javax.imageio.ImageIO;

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(); 

    /**
     * 处理缩略图,并返回新生成图片的相对值路径
     * @param thumbnail
     * @param targetAddr
     * @return
     */
    public static String generateThumbnail(File thumbnail,String targetAddr) {
        String realFileName = getRandomFileName();
        String extension = getFileExtension(thumbnail);
        makeDirPath(targetAddr);
        String relativeAddr  =targetAddr +realFileName + extension;
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);
        try {
            Thumbnails.of(thumbnail).size(200, 200)
            .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath + "watermark.png")),0.25f)
            .outputQuality(0.8f).toFile(dest);
        }catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /**
     * 创建目标路径所涉及到的目录,即/home/work/o2o/xxx.jpg,
     * 那么 home work o2o 这三个文件夹都得自动创建
     * @param targetAddr
     */
    private static void makeDirPath(String targetAddr) {
        // TODO Auto-generated method stub
        String realFileParentPath = PathUtil.getImgBasePath()+targetAddr;
        File dirPath = new File(realFileParentPath);
        if(!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }


    /**
     * 生成随机文件名,当前年月日小时分钟秒+五位随机数
     */
    private static String getRandomFileName() {
        //获取随机的五位数
        int rannum = r.nextInt(89999) + 10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return nowTimeStr+rannum;
    }
    /**
     * 获取输入文件流的扩展名
     * @param args
     * @throws IOException
     */
    private static String getFileExtension(File thumbnail) {
        String originalFileName = thumbnail.getName();
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }
    public static void main(String[] args) throws IOException {

        Thumbnails.of(new File("/Users/mac/Downloads/luoto.png")).size(200, 200)
                .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/jingyu.png")), 0.25f)
                .outputQuality(0.8f).toFile("/Users/mac/Downloads/luotonew.png");
    }
}


4.4 Dto之ShopExecution的实现

创建枚举类型文件

这里写图片描述

package com.imooc.o2o.enums;

public enum ShopStateEnum {

    CHECK(0, "审核中"), OFFLINE(-1, "非法店铺"), SUCCESS(1, "操作成功"), PASS(2, "通过认证"), INNER_ERROR(-1001, "内部系统错误"),
    NULL_SHOPID(-1002,"ShopId为空");
    private int state;
    private String stateInfo;

    private ShopStateEnum(int state, String stateInfo) {
        this.state = state;
        this.stateInfo = stateInfo;
    }

    /*
     *依据传入的state返回相应的enum值 
     */
    public static ShopStateEnum stateOf(int state) {
        for(ShopStateEnum stateEnum:values()) {
            if(stateEnum.getState() == state) {
                return stateEnum;
            }
        }
        return null;
    }

    public int getState() {
        return state;
    }

    public String getStateInfo() {
        return stateInfo;
    }

}

src/main/java/com.imooc.o2o.dto路径下创建ShopExecution.java类

package com.imooc.o2o.dto;

import java.util.List;

import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;

public class ShopExecution {

    // 结果状态
    private int state;

    // 状态标识
    private String stateInfo;

    // 店铺数量
    private int count;

    // 操作的shop(增删改店铺的时候用到)
    private Shop shop;

    // shop列表(查询店铺列表的时候使用)
    private List<Shop> shopList;

    public ShopExecution() {

    }

    // 店铺操作失败的时候使用的构造器
    public ShopExecution(ShopStateEnum stateEnum) {
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();
    }

    // 店铺操作成功的时候使用的构造器
    public ShopExecution(ShopStateEnum stateEnum, Shop shop) {
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();
        this.shop = shop;
    }

    // 店铺操作成功的时候使用的构造器
    public ShopExecution(ShopStateEnum stateEnum, List<Shop> shopList) {
        this.state = stateEnum.getState();
        this.stateInfo = stateEnum.getStateInfo();
        this.shopList = shopList;
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    public String getStateInfo() {
        return stateInfo;
    }

    public void setStateInfo(String stateInfo) {
        this.stateInfo = stateInfo;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public Shop getShop() {
        return shop;
    }

    public void setShop(Shop shop) {
        this.shop = shop;
    }

    public List<Shop> getShopList() {
        return shopList;
    }

    public void setShopList(List<Shop> shopList) {
        this.shopList = shopList;
    }


}

4.5 店铺注册之Service层的实现

创建com.imooc.o2o.exceptions包,ShopOperationException.java类文件

package com.imooc.o2o.exceptions;

public class ShopOperationException extends RuntimeException{

    /**
     * 
     */
    private static final long serialVersionUID = 2361446884822298905L;

    public ShopOperationException(String msg) {
        super(msg);
    }
}

ShopServiceImpl.java

package com.imooc.o2o.service.impl;

import java.io.File;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.imooc.o2o.dao.ShopDao;
import com.imooc.o2o.dto.ShopExecution;
import com.imooc.o2o.entity.Shop;
import com.imooc.o2o.enums.ShopStateEnum;
import com.imooc.o2o.exceptions.ShopOperationException;
import com.imooc.o2o.service.ShopService;
import com.imooc.o2o.util.ImageUtil;
import com.imooc.o2o.util.PathUtil;

@Service
public class ShopServiceImpl implements ShopService{

    @Autowired
    private ShopDao shopDao;
    @Override
    @Transactional
    public ShopExecution addShop(Shop shop, File shopImg) {
        //空值判断
        if(shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP);
        }
        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(shopImg !=null) {
                    //存储图片
                    try {
                        addShopImg(shop, shopImg);
                    }catch (Exception e) {
                        // TODO: handle exception
                        throw new ShopOperationException("addShopImg error"+e.getMessage());
                    }
                    //更新店铺的图片地址
                    effectedNum = shopDao.updateShop(shop);
                    if(effectedNum <=0) {
                        throw new  ShopOperationException("更新图片地址失败");
                    }

                }
            }
        }catch (Exception e) {
            // TODO: handle exception
            throw new ShopOperationException("addShop error:"+e.getMessage());
        }
        return new ShopExecution(ShopStateEnum.CHECK,shop);
    }
    private void addShopImg(Shop shop, File shopImg) {
        // 获取shop图片目录的相对值路径
                String dest = PathUtil.getShopImagePath(shop.getShopId());
                String shopImgAddr = ImageUtil.generateThumbnail(shopImg,dest);
                shop.setShopImg(shopImgAddr);
    }
}

src/test/java/com.imooc.o2o.service目录下创建ShopServiceTest.java文件

package com.imooc.o2o.service;

import static org.junit.Assert.assertEquals;

import java.io.File;
import java.util.Date;

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

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

public class ShopServiceTest extends BaseTest{

    @Autowired
    private ShopService shopService;

    @Test
    public void testAddShop() {
        Shop shop = new Shop();
        PersonInfo owner = new PersonInfo();
        Area area = new Area();
        ShopCategory shopCategory = new ShopCategory();
        owner.setUserId(1L);
        area.setAreaId(2);
        shopCategory.setShopCategoryId(1L);
        shop.setOwner(owner);
        shop.setArea(area);
        shop.setShopCategory(shopCategory);
        shop.setShopName("测试的店铺1");
        shop.setShopDesc("test1");
        shop.setShopAddr("test1");
        shop.setPhone("test1");
        shop.setCreateTime(new Date());
        shop.setEnableStatus(ShopStateEnum.CHECK.getState());
        shop.setAdvice("审核中");
        File shopImg = new File("/Users/mac/Downloads/luoto.png");
        ShopExecution se = shopService.addShop(shop, shopImg);
        assertEquals(ShopStateEnum.CHECK.getState(), se.getState());
    }
}

运行JUnit进行测试,运行成功,但是报错了显示不能创建file

这里写图片描述

修改PathUtil.java,去掉"upkoad/item/shop/"+ shopId + "/"; upkoad前的斜杠

//根据不同的业务需求返回不同的子路径
    public static String getShopImagePath(long shopId) {
        String imagePath = "upkoad/item/shop/"+ shopId + "/";
        return imagePath.replace("/", seperator);
    }

在src/test/resources目录下添加watermark.png水印图片再进行测试,测试成功,文件也创建成功了。注意:PathUtil.java中设置的文件路径需要真实存在。

4.6 店铺注册之前端设计

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 22
    评论
### 回答1: 这个问题似乎是一个编码问题,如果是想问如何将使用SSM框架的Java应用程序转移到使用Spring Boot应用程序并在校园商铺全栈开发中使用的问题,可以遵循以下步骤: 1. 确定Spring Boot的版本和构建工具,例如Maven或Gradle。 2. 导入所需的Spring Boot依赖项和其他必要的库。 3. 将配置文件从XML格式转换为注释配置类。 4. 根据需要更改应用程序的代码,例如更新Spring MVC控制器,更改持久层代码等。 5. 如果需要将原始数据迁移到新的Spring Boot应用程序中,可以编写脚本或使用Spring Data JPA来迁移数据。 6. 测试新的Spring Boot应用程序并修复错误。 当选择将SSM框架的Java应用程序转移到Spring Boot应用程序时,应该考虑Spring Boot的优点和功能,例如自动配置,简化的部署,更易于管理的依赖项等。 ### 回答2: Java双版本指的是使用不同的框架版本,实现同一项目的开发SSMSpringBoot都是Java开发中常用的框架,它们各有特点,可以适用于不同的项目需求。 在校园商铺全栈开发中,使用SSM则需要手动配置很多东西,比如配置Mybatis、SpringMVC和Spring等,开发效率相对较低。而使用SpringBoot则可以快速搭建整个项目骨架,自动化配置等,提高了开发效率,同时也更加易于维护和扩展。 在具体的开发中,可以先按照需求分析和设计,搭建数据库,并完成数据表的设计和创建。然后根据业务需求,在控制器层,编写对应的接口,实现业务逻辑处理。同时也要编写相应的实体类、服务类和数据访问层等,完成整个项目的后端实现。 在前端方面,根据项目需求,可以选择使用一些前端框架,比如Vue或React等,编写对应的HTML、CSS和JavaScript等前端代码,实现页面的渲染。 最后,需要进行整个项目的集成测试,确保各个功能正常运行,并进行部署操作。可以使用一些云服务提供商,将项目部署在云服务器上,实现快速部署和升级。 总之,Java开发中的双版本技术,可以让我们根据不同项目需求,选择不同的框架开发,提高开发效率和代码质量,实现更加优秀和完善的项目。 ### 回答3: 本回答将从以下几个方面来介绍java双版本(ssmspringboot校园商铺全栈开发。 一、SSM版本开发 在使用SSM版本进行校园商铺全栈开发时,可使用Spring作为底层框架,Mybatis作为数据访问层框架,SpringMVC作为控制层框架。这些框架是互相独立的,整合在一起可快速开发出具有复杂业务逻辑的Web应用程序。在使用SSM版本进行开发时需要进行如下步骤: 1.搭建开发环境:安装JDK、Tomcat、Maven等必要工具,配置好环境变量和项目配置文件。 2.设计数据库:根据需求设计数据库表,使用Mybatis提供的逆向工程生成映射文件和实体类。 3.编写业务逻辑:使用SpringMVC编写控制层代码,将请求分发到不同的方法中,使用Mybatis编写数据访问层代码,实现SQL语句的执行和结果的处理。 4.整合框架:在项目中将Spring、Mybatis和SpringMVC整合起来,通过XML配置文件进行配置,实现框架的快速开发。 二、Spring Boot版本开发 Spring Boot是基于Spring框架的一种新型开发模式,它可以帮助开发者更快地搭建基于Spring框架的项目。在使用Spring Boot版本进行校园商铺全栈开发时,开发者可以使用Spring Boot自带的一些模块,如Spring Boot Starter Web、Spring Boot Starter JDBC等。 1.搭建开发环境:安装JDK、IDE工具(IntelliJ IDEA或Eclipse等),了解并掌握Maven和Gradle构建工具。 2.配置数据库:Spring Boot默认使用嵌入式的H2数据库,如果需要使用MySQL、Oracle等数据库,需要在配置文件中进行配置。 3.编写业务逻辑:使用Spring Boot Starter Web提供的RestController注解编写控制层代码,使用Spring Boot Starter JDBC提供的JdbcTemplate类进行数据访问操作。 4.整合框架:Spring Boot已经将Spring框架的一些常用模块集成在了一起,使得整合过程变得十分简单。只需要添加相应的Starter包,在application.properties中配置一些参数即可。 总之,在进行校园商铺全栈开发时,希望开发者可以深入了解SSM和Spring Boot框架的特点和原理,选择最适合自己的开发模式。同时,结合个人的实际情况和项目需求,选择适当的工具和开发方式,并进行技术实践和提高。
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值