校园商铺-6店铺编辑列表和列表功能-7店铺列表展示之Controller层的实现

1.获取店铺的列表信息 getShopList

由于只需要通过用户名去获取owner下面的店铺列表,因此是get方法。
从0开始,个人创建的店铺是比较少的,不需要做分页,100个店铺也是极限。

2.开发店铺管理页面对应的controller方法 getShopManagementInfo

当你直接访问这个页面且不经过登录,或不从店铺列表进来,就重定向到店铺列表。说明这次是违规操作,不能直接访问这个页面。
如果之前已经登录过这个系统,就有权限访问店铺管理页,我们就将重定向设为false。一旦传入店铺ID,就有权限对店铺做操作。
有没有权限,可以通过拦截器实现
从前端请求获取店铺ID:

  • 1.如果ID不存在,就从Session中获取:如果Session也不存在,就重定向到店铺列表页;否则将Session中的店铺ID返回
  • 2.如果ID存在,就返回店铺ID(示例可能有错)
package com.csj2018.o2o.web.shopadmin;

import java.io.File;
import java.io.FileOutputStream;
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 java.io.InputStream;
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.csj2018.o2o.dto.ShopExecution;
import com.csj2018.o2o.entity.Area;
import com.csj2018.o2o.entity.PersonInfo;
import com.csj2018.o2o.entity.Shop;
import com.csj2018.o2o.entity.ShopCategory;
import com.csj2018.o2o.enums.ShopStateEnum;
import com.csj2018.o2o.exceptions.ShopOperationException;
import com.csj2018.o2o.service.AreaService;
import com.csj2018.o2o.service.ShopCategoryService;
import com.csj2018.o2o.service.ShopService;
import com.csj2018.o2o.util.CodeUtil;
import com.csj2018.o2o.util.HttpServletRequestUtil;
import com.csj2018.o2o.util.ImageUtil;
import com.csj2018.o2o.util.PathUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

// 首先在Controller里面定义了SpringMVC相关的标签,这个标签包含了Controller的访问路径以及registerregisterShop方法的访问路径,
@Controller
@RequestMapping("/shopadmin")
public class ShopManagerController {
	// 同时给它在执行的时候通过Spring容器注入之前实现好的ShopService实现类,用来提供addShop的服务。
	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;
	
	//6-7新增
	@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
	public Map<String,Object> getShopList(HttpServletRequest request){
		Map<String,Object> modelMap = new HashMap<>();
		//确保user不为空
		PersonInfo user = new PersonInfo();
		user.setUserId(1L);
		user.setName("test");
		request.getSession().setAttribute("user", user);
		user = (PersonInfo) request.getSession().getAttribute("user");
		try {
			Shop shopCondition = new Shop();
			shopCondition.setOwner(user);
			ShopExecution se = shopService.getShopList(shopCondition, 0, 100);
			modelMap.put("shopList", se.getShopList());
			modelMap.put("user", user);
			modelMap.put("success", true);
		}catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
		}
		return modelMap;
	}
	
	@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(HttpServletRequest request){
		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;
		
	}
	@RequestMapping(value = "/registershop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> registerShop(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//1.验证码校验
		if(!CodeUtil.checkVerifyCode(request)) {
			modelMap.put("success", "false");
			modelMap.put("message", "输入了错误的验证码");
			return modelMap;
		}
		//2.获取请求头的店铺信息 接收从前台传递的shopStr对象,将这个对象转换成Shop实体类
		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("errMeg", e.getMessage());
			return modelMap;
		}
		// 3.获取图片 将请求中的文件流从CommonsMultipartResolver解析为CommonsMultipartFile
		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;
		}
		// 4.注册店铺
		if (shop != null && shopImg != null) {
			/*
			 * 添加Session
			 * 注册店铺或对店铺做操作,是需要登陆的
			 */
			PersonInfo owner = new PersonInfo();
			owner.setUserId(1L);
			request.getSession().setAttribute("user", owner);
			PersonInfo owner2 = (PersonInfo) request.getSession().getAttribute("user");
			shop.setOwner(owner2);
			
			/*
			 * 由于addShop的第二个参数是File类型的,而传入的ShopImg是CommonsMultipartFile这样的一个类型,因此需要将CommonsMultipartFile转换成File类型
			 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 (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
				return modelMap;
			}
			 */
			ShopExecution se;
			try {
				se = shopService.addShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
				if (se.getState() == ShopStateEnum.CHECK.getState()) {
					/*
					 * 在店铺添加完成后,还需要做Session的操作。用户和店铺的关系是一对多的,即一个owner能够创建多个店铺。
					 * 因此需要在Session里面保存一个店铺列表来显示用户可以操作的店铺。
					 */
					@SuppressWarnings("unchecked")
					List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
					if(shopList == null || shopList.size() == 0) {
						shopList = new ArrayList<Shop>();
					}
					shopList.add(se.getShop());
					request.getSession().setAttribute("shopList", shopList);
					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;
		}

	}
	
	@RequestMapping(value = "/modifyshop", method = RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> modifyShop(HttpServletRequest request) {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		//1.验证码校验
		if(!CodeUtil.checkVerifyCode(request)) {
			modelMap.put("success", "false");
			modelMap.put("message", "输入了错误的验证码");
			return modelMap;
		}
		
		//2.获取请求头的店铺信息 接收从前台传递的shopStr对象,将这个对象转换成Shop实体类
		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("errMeg", e.getMessage());
			return modelMap;
		}
		// 3.获取图片 将请求中的文件流从CommonsMultipartResolver解析为CommonsMultipartFile
		CommonsMultipartFile shopImg = null;
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
		}
		
		// 2.修改店铺
		if (shop != null && shop.getShopId() != null) {
			//由于图片是可上传、可不上传的,因此图片非空判断去除;取而代之确保shopId不为空
			//修改店铺信息不用从session获取用户信息
			PersonInfo owner = new PersonInfo();
			// 预期从Session获取,目前自定义,以后完善
			owner.setUserId(1L);
			shop.setOwner(owner);
			// 由于addShop的第二个参数是File类型的,而传入的ShopImg是CommonsMultipartFile这样的一个类型,因此需要将CommonsMultipartFile转换成File类型
/*
 * 这块代码,教程没有
			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 (Exception e) {
				modelMap.put("success", false);
				modelMap.put("errMsg", e.getMessage());
				return modelMap;
			}
*/
			
			ShopExecution se;
			try {
				if(shopImg == null) {
					se = shopService.modifyShop(shop, null, null);
				}else {
					se = shopService.modifyShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
				}
				if (se.getState() == ShopStateEnum.SUCCESS.getState()) {
					modelMap.put("success", true);
				} else {
					modelMap.put("success", false);
					modelMap.put("errMsg", se.getStateInfo());	
				}
			}catch(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;
		}

	}
	private static void inputStreamToFile(InputStream inputStream, File file) {
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[1024];
			while ((bytesRead = inputStream.read(buffer)) > 0) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (Exception e) {
			throw new RuntimeException("调用inputStreamToFile产生异常:" + e.getMessage());
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				throw new RuntimeException("调用inputStreamToFile产生异常:" + e.getMessage());
			}
		}
	}
}
原文地址:https://www.cnblogs.com/csj2018/p/12404168.html