商铺项目(店铺注册功能模块(三))
下面来写Controller层:
package com.ouyan.o2o.web.shopadmin; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; 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.PersonInfo; import com.ouyan.o2o.entity.Shop; import com.ouyan.o2o.enums.ShopStateEnum; import com.ouyan.o2o.service.ShopService; import com.ouyan.o2o.util.HttpServletRequestUtil; import com.ouyan.o2o.util.PathUtil; import com.ouyan.o2o.util.imageUtil; @Controller @RequestMapping("/shopadmin") public class ShopManagementController { @Autowired private ShopService shopService; @RequestMapping(value = "/registershop", method = RequestMethod.POST) @ResponseBody public Map<String, Object> registerShop(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); // 接受并转化相应参数 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 = new PersonInfo(); owner.setUserId(1L); shop.setOwner(owner); File shopImgFile = new File(PathUtil.getImgBasePath() + imageUtil.getRandomFileName()); try { shopImgFile.createNewFile(); } catch (IOException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); return modelMap; } try { inputStreamToFile(shopImg.getInputStream(), shopImgFile); } catch (IOException e) { modelMap.put("success", false); modelMap.put("errMsg", e.getMessage()); return modelMap; } ShopExecution se = shopService.addShop(shop, shopImgFile); if(se.getState()==ShopStateEnum.CHECK.getState()){ modelMap.put("success", true); }else{ modelMap.put("success", false); modelMap.put("errMsg", se.getStateInfo()); } } else { modelMap.put("success", false); modelMap.put("errMsg", "请输入店铺信息"); return modelMap; } return modelMap; } private static void inputStreamToFile(InputStream ins, File file) { FileOutputStream os = null; try { os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = ins.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } } catch (Exception e) { throw new RuntimeException("调用inputStreamToFile产生异常" + e.getMessage()); } finally { try { if (os != null) { os.close(); } if (ins != null) { ins.close(); } } catch (IOException e) { throw new RuntimeException("inputStreamToFile关闭io产生异常" + e.getMessage()); } } } }
改造Controller(五个文件):
package com.ouyan.o2o.web.shopadmin; import java.io.IOException; import java.util.HashMap; 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.PersonInfo; 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.HttpServletRequestUtil; @Controller @RequestMapping("/shopadmin") public class ShopManagementController { @Autowired private ShopService shopService; @RequestMapping(value = "/registershop", method = RequestMethod.POST) @ResponseBody public Map<String, Object> registerShop(HttpServletRequest request) { Map<String, Object> modelMap = new HashMap<String, Object>(); // 接受并转化相应参数 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 = new PersonInfo(); // session TODO owner.setUserId(1L); shop.setOwner(owner); ShopExecution se; try { se = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename()); if (se.getState() == ShopStateEnum.CHECK.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", "请输入店铺信息"); return modelMap; } } }
package com.ouyan.o2o.service; import java.io.InputStream; import com.ouyan.o2o.dto.ShopExecution; import com.ouyan.o2o.entity.Shop; public interface ShopService { ShopExecution addShop(Shop shop,InputStream shopImgInputStream,String fileName); }
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 IOException { //获取shop图片的相对路径 String dest = PathUtil.getShopImagePath(shop.getShopId()); String shopImgAddr = imageUtil.generateThumbnail(shopImgInputStream,fileName,dest); shop.setShopImg(shopImgAddr); } }
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"); } }
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 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()); } }