-
商店名称
-
商店分类
-
所属区域
-
详细地址
-
联系电话
-
缩略图
-
商店简介
shopService:
public interface ShopService {
ShopExecution addShop(Shop shop,File shopImg);
}
shopServiceImpl:
@Service
public class ShopServiceImpl implements ShopService{
@Autowired
private ShopDao shopDao;
//非空判断 事务支持
@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) {
//使用ShopOperationException 事务才会回滚
throw new ShopOperationException("店铺创建失败");
//成功
}else {
if(shopImg != null) {
try {
//用shop的id创建图片目录,将图片地址跟新到shop
addShopImg(shop,shopImg);
}catch(Exception e) {
throw new ShopOperationException("addShopImg error"+e.getMessage());
}
//更新店铺图片地址
effectedNum = shopDao.updateShop(shop);
if(effectedNum<=0) {
//使用ShopOperationException 事务才会回滚
throw new ShopOperationException("更新图片地址失败");
//成功
}
}
}
//获取id进行下一步操作
}catch(Exception e) {
throw new ShopOperationException("addShop error");
}
return new ShopExecution(ShopStateEnum.CHECK,shop);
}
private void addShopImg(Shop shop, File shopImg) {
//获取图片目录的相对路径
String dest = PathUtil.getShopImagePath(shop.getShopId());
//存储图片,返回绝对值路径
String shopImgAddr = ImageUtil.generateThumbnail(shopImg, dest);
shop.setShopImg(shopImgAddr);
}
}
自定义异常类: ShopOperationException
public class ShopOperationException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = -1130600480095693708L;
public ShopOperationException(String msg) {
super(msg);
}
}
测试:ShopServiceTest
@Service
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("测试店铺3");
shop.setShopDesc("test3");
shop.setShopAddr("test3");
shop.setPhone("test3");
shop.setCreateTime(new Date());
shop.setEnableStatus(ShopStateEnum.CHECK.getState());
shop.setAdvice("审核中");
// //第一个是转义,第二个是/ 一般window用\加上转义就变成了\\
File shopImg = new File("F:/schoolPicture/xiaohuangren.jpg");
ShopExecution se = shopService.addShop(shop, shopImg);
assertEquals(ShopStateEnum.CHECK.getState(), se.getState());
}
}
注意:原视频中在PathUtil类中的getImgBasePath方法和getShopImagePath方法中有将路径进行转换的操作,楼主这里不知为何报错,就直接返回了
测试通过。
–1.访问地址`http://m.sui.taobao.org/demos/form/label-input
–2.复制源代码
–3 用以下代码替换掉源代码的css`、js
修改页面显示;
如下:
shopoperation.html:
SUI Mobile Demo
增加controller路由访问:
@Controller
@RequestMapping(value = "/shop",method= {RequestMethod.GET})
public class ShopAdminController {
@RequestMapping(value = "/shopoperation")
public String shopOperation() {
return "shop/shopoperation";
}
}
工具类:HttpServletRequestUtil
public class HttpServletRequestUtil {
public static int getInt(HttpServletRequest request,String key) {
try {
return Integer.decode(request.getParameter(key));
}catch(Exception e) {
return -1;
}
}
public static long getLong(HttpServletRequest request,String key) {
try {
return Long.valueOf(request.getParameter(key));
}catch(Exception e) {
return -1;
}
}
public static Double getDouble(HttpServletRequest request,String key) {
try {
return Double.valueOf(request.getParameter(key));
}catch(Exception e) {
return -1d;
}
}
public static boolean getBoolean(HttpServletRequest request,String key) {
try {
return Boolean.valueOf(request.getParameter(key));
}catch(Exception e) {
return false;
}
}
public static String getString(HttpServletRequest request,String key) {
try {
String result = request.getParameter(key);
if(result != null) {
result = result.trim();
}if("".equals(result)) {
result = null;
}
return result;
}catch(Exception e) {
return null;
}
}
}
控制器:ShopManagementController
/*
* 店铺管理
*/
@Controller
@RequestMapping(value = "/shopadmin")
public class ShopManagementController {
@Autowired
private ShopService shopService;
@RequestMapping(value = "/registershop", method = { RequestMethod.POST })
@ResponseBody
private Map registerShop(HttpServletRequest request) {
Map modelMap = new HashMap();
// 1.接收、转化参数,店铺信息、图片
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;
}
// 2.注册商店
if(shop != null && shopImg != null) {
PersonInfo owner = new PersonInfo();
//session todo
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());
}
return modelMap;
}else {
modelMap.put("success", false);
modelMap.put("errMsg", "请输入店铺信息");
return modelMap;
}
// 3.返回结果
}
//文件转换
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关闭异常"+e.getMessage());
}
}
}
}
shopoperation.js
/**
* 1.从后台获取到店铺分类等信息填充到前台控件
* 2.获取到信息,转发到后台注册店铺
*/
$(function(){
var initUrl = '/o2o/shopadmin/getshopinitinfo';
var registerShopUrl = '/o2o/shopadmin/registershop';
alert(initUrl);
getShopInitInfo();
function getShopInitInfo() {
$.getJSON(initUrl,function(data){
if(data.success){
var tempHtml = '';
var tempAreaHtml = '';
data.shopCategoryList.map(function(item,index){
tempHtml += '';
});
data.areaList.map(function(item,index){
tempAreaHtml += '';
});
$('#shop-category').html(tempHtml);
$('#area').html(tempAreaHtml);
}
});
/*
* 点击提交的时候,获取到表单内容
*/
$('#submit').click(function(){
var shop = {};
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();
formDate.append('shopImg',shopImg);
formDate.append('shopStr',JSON.stringify(shop));
$.ajax({
url:registerShopUrl,
type:'POST',
data:formData,
contentType:false,
proceesData:false,
cache:false,
success:function(data){
if(data.success){
$.toast('提交成功!');
}else{
$.toast('提交失败!'+data.errMsg);
}
}
})
})
}
})
ShopManagementController:
/*
* 店铺管理
*/
@Controller
@RequestMapping(value = "/shopadmin")
public class ShopManagementController {
@Autowired
private ShopService shopService;
@RequestMapping(value = "/registershop", method = { RequestMethod.POST })
@ResponseBody
private Map registerShop(HttpServletRequest request) {
Map modelMap = new HashMap();
// 1.接收、转化参数,店铺信息、图片
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;
}
// 2.注册商店
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 (IOException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
}
return modelMap;
}else {
modelMap.put("success", false);
modelMap.put("errMsg", "请输入店铺信息");
return modelMap;
}
}
}
ShopService:
public interface ShopService {
ShopExecution addShop(Shop shop,InputStream shopImgInputStream,String fileName);
}
ShopServiceImpl:
@Service
public class ShopServiceImpl implements ShopService{
@Autowired
private ShopDao shopDao;
//非空判断 事务支持
@Transactional
public ShopExecution addShop(Shop shop,InputStream shopImgInputStream,String fileName) {
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) {
//使用ShopOperationException 事务才会回滚
throw new ShopOperationException("店铺创建失败");
//成功
}else {
if(shopImgInputStream != null) {
try {
//用shop的id创建图片目录,将图片地址跟新到shop
addShopImg(shop,shopImgInputStream,fileName);
}catch(Exception e) {
throw new ShopOperationException("addShopImg error"+e.getMessage());
}
//更新店铺图片地址
effectedNum = shopDao.updateShop(shop);
if(effectedNum<=0) {
//使用ShopOperationException 事务才会回滚
throw new ShopOperationException("更新图片地址失败");
//成功
}
}
}
//获取id进行下一步操作
}catch(Exception e) {
throw new ShopOperationException("addShop error");
}
return new ShopExecution(ShopStateEnum.CHECK,shop);
}
private void addShopImg(Shop shop, InputStream shopImgInputStream,String fileName) {
//获取图片目录的相对路径
String dest = PathUtil.getShopImagePath(shop.getShopId());
//存储图片,返回绝对值路径
String shopImgAddr = ImageUtil.generateThumbnail(shopImgInputStream,fileName, dest);
shop.setShopImg(shopImgAddr);
}
}
ImageUtil:
/*
* 改变图片大小,添加水印,将图片压缩,输出在同级目录底下
*/
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();
//处理缩列图(商品小图,店铺门面照) 文件处理对象 文件存储路径
public static String generateThumbnail(InputStream shopImg,String fileName,String targetAddr){
//统一命名
String realFileName = getRandomFileName();
//获取扩展名
String extension = getFileExtension(fileName);
makeDirPath(targetAddr);
//生成唯一相对路径
String relativeAddr = targetAddr + realFileName + extension;
System.out.println("子路径:"+relativeAddr);
//根路径+先对路径==文件路径
File dest = new File(PathUtil.getImgBasePath()+relativeAddr);
System.out.println("绝对路径"+dest);
try {
Thumbnails.of((shopImg)).size(200, 200) //项目resource下
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath+"watermark.png")),0.25f)
.outputQuality(0.8f) //压缩比 输出位置
.toFile(dest);
}catch(IOException e) {
e.printStackTrace();
}
return relativeAddr;
}
//创建目标路径所涉及到目录 /home/work/xiangze/xxx.jpg
//那么home work xiangze 三个文件夹都自动创建
private static void makeDirPath(String targetAddr) {
//全路径
String realFileParentPath = PathUtil.getImgBasePath()+targetAddr;
File dirPath = new File(realFileParentPath);
if(!dirPath.exists()) {
dirPath.mkdirs();
}
}
//获取输入文件流的扩张名 .jpg
private static String getFileExtension(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}
/*
* 生成随机文件名 当前时间+5位随机数
*/
public static String getRandomFileName() {
//获取随机5位数 10000-89999
int rannum = r.nextInt(89999) + 10000;
String nowTimeStr = sDateFormat.format(new Date());
return nowTimeStr+rannum;
}
public static void main(String[] args) throws Exception {
//处理图片文件的路径 输出图片大小 图片添加水印
Thumbnails.of(new File("F:/schoolPicture/xiaohuangren.jpg"))
.size(200, 200) //水印位置 水印图片路径
.watermark(Positions.BOTTOM_RIGHT, //透明度
ImageIO.read(new File(basePath+"watermark.png")),0.25f)
.outputQuality(0.8f) //压缩比 输出位置
.toFile("F:/schoolPicture/xiaohuangrennew2.jpg");
}
}
ShopServiceTest:
@Service
public class ShopServiceTest extends BaseTest{
@Autowired
private ShopService shopService;
@Test
public void testAddShop() throws Exception {
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("测试店铺4");
shop.setShopDesc("test4");
shop.setShopAddr("test4");
shop.setPhone("test4");
shop.setCreateTime(new Date());
shop.setEnableStatus(ShopStateEnum.CHECK.getState());
shop.setAdvice("审核中");
// //第一个是转义,第二个是/ 一般window用\加上转义就变成了\\
File shopImg = new File("F:/schoolPicture/xiaohuangren.jpg");
InputStream is = new FileInputStream(shopImg);
ShopExecution se = shopService.addShop(shop, is,shopImg.getName());
assertEquals(ShopStateEnum.CHECK.getState(), se.getState());
}
}
测试完成????