noaman_wgs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

一、主要功能概述

前台门户:                                                                                                 后台:

 

二、主要学习到的知识点

主要接口设计

运营后台

1.产品list:/manage/product/list.do
2.产品搜索:/manage/product/search.do
3.图片上传:/manage/product/upload.do
4.产品详情:/manage/product/detail.do
5.产品上下架:/manage/product/set_sale_status.do
6.新增OR更新产品:/manage/product/save.do
7.富文本上传图片:/manage/product/richtext_img_upload.do

门户

1.产品搜索及动态排序List:/product/list.do
2.产品detail:/product/detail.do

 

三、数据表设计

四、DAO层

package com.mmall.dao;

import com.mmall.pojo.Product;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface ProductMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Product record);

    int insertSelective(Product record);

    Product selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Product record);

    int updateByPrimaryKey(Product record);

    List<Product> selectProductList();

    List<Product> selectByNameAndId(@Param("productName") String productName,
                                    @Param("productId") Integer productId);

    List<Product> selectByNameAndCategoryIds(@Param("keyword") String productName,
                                               @Param("categoryList") List<Integer> categoryList);


}
View Code

Mapper:

ProductMapper.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.mmall.dao.ProductMapper" >
  <resultMap id="BaseResultMap" type="com.mmall.pojo.Product" >
    <constructor >
      <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="category_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="name" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="subtitle" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="main_image" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="sub_images" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="detail" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="price" jdbcType="DECIMAL" javaType="java.math.BigDecimal" />
      <arg column="stock" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="status" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
      <arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    id, category_id, name, subtitle, main_image, sub_images, detail, price, stock, status, 
    create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from mmall_product
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from mmall_product
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.mmall.pojo.Product" >
    insert into mmall_product (id, category_id, name, 
      subtitle, main_image, sub_images, 
      detail, price, stock, 
      status, create_time, update_time
      )
    values (#{id,jdbcType=INTEGER}, #{categoryId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, 
      #{subtitle,jdbcType=VARCHAR}, #{mainImage,jdbcType=VARCHAR}, #{subImages,jdbcType=VARCHAR}, 
      #{detail,jdbcType=VARCHAR}, #{price,jdbcType=DECIMAL}, #{stock,jdbcType=INTEGER}, 
      #{status,jdbcType=INTEGER}, now(), now()
      )
  </insert>
  <insert id="insertSelective" parameterType="com.mmall.pojo.Product" >
    insert into mmall_product
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="categoryId != null" >
        category_id,
      </if>
      <if test="name != null" >
        name,
      </if>
      <if test="subtitle != null" >
        subtitle,
      </if>
      <if test="mainImage != null" >
        main_image,
      </if>
      <if test="subImages != null" >
        sub_images,
      </if>
      <if test="detail != null" >
        detail,
      </if>
      <if test="price != null" >
        price,
      </if>
      <if test="stock != null" >
        stock,
      </if>
      <if test="status != null" >
        status,
      </if>
      <if test="createTime != null" >
        create_time,
      </if>
      <if test="updateTime != null" >
        update_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=INTEGER},
      </if>
      <if test="categoryId != null" >
        #{categoryId,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="subtitle != null" >
        #{subtitle,jdbcType=VARCHAR},
      </if>
      <if test="mainImage != null" >
        #{mainImage,jdbcType=VARCHAR},
      </if>
      <if test="subImages != null" >
        #{subImages,jdbcType=VARCHAR},
      </if>
      <if test="detail != null" >
        #{detail,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        #{price,jdbcType=DECIMAL},
      </if>
      <if test="stock != null" >
        #{stock,jdbcType=INTEGER},
      </if>
      <if test="status != null" >
        #{status,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        now(),
      </if>
      <if test="updateTime != null" >
        now(),
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.mmall.pojo.Product" >
    update mmall_product
    <set >
      <if test="categoryId != null" >
        category_id = #{categoryId,jdbcType=INTEGER},
      </if>
      <if test="name != null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="subtitle != null" >
        subtitle = #{subtitle,jdbcType=VARCHAR},
      </if>
      <if test="mainImage != null" >
        main_image = #{mainImage,jdbcType=VARCHAR},
      </if>
      <if test="subImages != null" >
        sub_images = #{subImages,jdbcType=VARCHAR},
      </if>
      <if test="detail != null" >
        detail = #{detail,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        price = #{price,jdbcType=DECIMAL},
      </if>
      <if test="stock != null" >
        stock = #{stock,jdbcType=INTEGER},
      </if>
      <if test="status != null" >
        status = #{status,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null" >
        update_time = now(),
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.mmall.pojo.Product" >
    update mmall_product
    set category_id = #{categoryId,jdbcType=INTEGER},
      name = #{name,jdbcType=VARCHAR},
      subtitle = #{subtitle,jdbcType=VARCHAR},
      main_image = #{mainImage,jdbcType=VARCHAR},
      sub_images = #{subImages,jdbcType=VARCHAR},
      detail = #{detail,jdbcType=VARCHAR},
      price = #{price,jdbcType=DECIMAL},
      stock = #{stock,jdbcType=INTEGER},
      status = #{status,jdbcType=INTEGER},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = now()
    where id = #{id,jdbcType=INTEGER}
  </update>

  <select id="selectProductList" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List"/>
    FROM mmall_product
    ORDER BY id ASC
  </select>

  <select id="selectByNameAndId" parameterType="map" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List"/>
    FROM  mmall_product
    <where>
      <if test="productName != null">
        AND name LIKE #{productName}
      </if>
      <if test="productName != null">
        AND id = #{productId}
      </if>
    </where>
  </select>

  <select id="selectByNameAndCategoryIds" parameterType="map" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List"/>
    FROM
    mmall_product
    WHERE status = 1
    <if test="productName != null">
      AND  name LIKE #{productName}
    </if>
    <if test="categoryList != null">
      and category_id in
      <foreach collection="categoryList" item="item" index="index" open="(" separator="," close=")">
        #{item}
      </foreach>
    </if>







  </select>
</mapper>
View Code

五、Service层

package com.mmall.service;

import com.github.pagehelper.PageInfo;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.vo.ProductDetailVo;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/10.
 */
public interface IProductService {

    ServerResponse saveOrUpdateProduct(Product product);

    ServerResponse<String> updateProductStatus(Integer productId, Integer status);

    ServerResponse<ProductDetailVo> manageGetProductDetail(Integer productId);

    ServerResponse<PageInfo> manageGetProductList(int pageNum, int pageSize);

    ServerResponse<PageInfo> searchProduct(String productName,
                                           Integer productId,
                                           int pageNum,
                                           int pageSize);

    ServerResponse<ProductDetailVo> getProductDetail(Integer productId);

    ServerResponse<PageInfo> getProductList(Integer categoryId, String keyword, int pageNum, int pageSize, String orderBy);
}
View Code

Impl:

package com.mmall.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.util.DateTimeUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/10.
 */
@Service("iProductService")
public class IProductServiceImpl implements IProductService {

    @Autowired
    ProductMapper productMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    ICategoryService iCategoryService;


    @Override
    public ServerResponse saveOrUpdateProduct(Product product){
        if (product != null){
            //设置活动页主页面
            if (product.getSubImages() != null){
                String[] subImagesArray = product.getSubImages().split(",");
                if (subImagesArray.length > 0){
                    product.setMainImage(subImagesArray[0]);
                }
            }

            // 新增
            if (product.getId() == null){
                int rowCount = productMapper.insert(product);
                if (rowCount > 0){
                    return ServerResponse.createBySuccess("新增产品成功");
                }else {
                    return ServerResponse.createByErrorMsg("新增产品失败");
                }
            }else {
                // 更新
                int rowCout = productMapper.updateByPrimaryKeySelective(product);
                if (rowCout > 0){
                    return ServerResponse.createBySuccess("更新产品成功");
                }else {
                    return ServerResponse.createByErrorMsg("更新产品失败");
                }

            }
        }
        return ServerResponse.createByErrorMsg("新增或更新产品参数为空");
    }


    @Override
    public ServerResponse<String> updateProductStatus(Integer productId, Integer status){
        if (productId != null && status != null){
            Product product = new Product();
            product.setId(productId);
            product.setStatus(status);
            int rowCount = productMapper.updateByPrimaryKeySelective(product);
            if (rowCount > 0){
                return ServerResponse.createBySuccess("修改产品状态成功");
            }else {
                return ServerResponse.createByErrorMsg("修改产品状态失败");
            }
        }else {
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
        }

    }

    @Override
    public ServerResponse<ProductDetailVo> manageGetProductDetail(Integer productId){
        if (productId == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null){
            return ServerResponse.createByErrorMsg("产品未上线或者已经下架");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);

    }

    //需要设置图片服务器URL, parentCategoryId, 时间转换等
    public ProductDetailVo assembleProductDetailVo(Product product){
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(product.getId());
        productDetailVo.setSubtitle(product.getSubtitle());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setMainImage(product.getMainImage());
        productDetailVo.setSubImages(product.getSubImages());
        productDetailVo.setCategoryId(product.getCategoryId());
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setName(product.getName());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setStock(product.getStock());

        //设置图片服务器URL
        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        //设置parentCategoryId
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category == null){
            productDetailVo.setParentCategoryId(0);
        }else {
            productDetailVo.setParentCategoryId(product.getCategoryId());
        }
        //设置时间
        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));

        return productDetailVo;
    }


    @Override
    public ServerResponse<PageInfo> manageGetProductList(int pageNum, int pageSize){
        //startPage--start
        //填充自己的sql查询逻辑
        //pageHelper-收尾
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productMapper.selectProductList();

        List<ProductListVo> productListVoList = Lists.newArrayList();
        for (Product product : productList){
            ProductListVo productListVo = assembleProductListVo(product);
            productListVoList.add(productListVo);
        }
        //给前端的是productListVO,但是需要productList进行分页
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    private ProductListVo assembleProductListVo(Product product){
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setName(product.getName());
        productListVo.setMainImage(product.getMainImage());
        productListVo.setImageHost((PropertiesUtil.getProperty("ftp.server.http.prefix","http://img.happymmall.com/")));
        productListVo.setPrice(product.getPrice());
        productListVo.setStatus(product.getStatus());
        productListVo.setSubTitle(product.getSubtitle());
        return productListVo;
    }

    @Override
    public ServerResponse<PageInfo> searchProduct(String productName,
                                                  Integer productId,
                                                  int pageNum,
                                                  int pageSize){
        if (StringUtils.isBlank(productName) && productId == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
        }

        PageHelper.startPage(pageNum, pageSize);
        productName = "%" + productName + "%";
        List<Product> productList = productMapper.selectByNameAndId(productName, productId);
        List<ProductListVo> productListVoList = Lists.newArrayList();
        for (Product product : productList){
            ProductListVo productListVo = assembleProductListVo(product);
            productListVoList.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);

    }




    /***************门户产品***************/
    @Override
    public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){
        if (productId == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
        }

        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null){
            return ServerResponse.createByErrorMsg("产品已下架或者未上线");
        }
        if (product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()){
            return ServerResponse.createByErrorMsg("产品已下架或者未上线");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }


    //根据categoryId找到一个品类的所有产品id。再遍历该品类下面产品id,得到产品详情
    @Override
    public ServerResponse<PageInfo> getProductList(Integer categoryId, String keyword, int pageNum, int pageSize, String orderBy){
        if (StringUtils.isBlank(keyword) && categoryId == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
        }

        //1 categoryId != null && keyword == null
        List<Integer> categoryList = Lists.newArrayList();
        if (categoryId != null){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category == null || StringUtils.isBlank(keyword)){
                //没有该分类,并且还没有关键字,这个时候返回一个空的结果集,不报错
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> productListVoList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVoList);
                return ServerResponse.createBySuccess(pageInfo);
            }else {
                categoryList = iCategoryService.getCategoryAndDeepChildrenCategory(category.getId()).getData();
            }
        }

        //2 keyword == null
        if (StringUtils.isNotBlank(keyword)){
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }

        PageHelper.startPage(pageNum, pageSize);
        //排序处理 PageHelper的排序参数格式:price asc; price desc;
        if (StringUtils.isNotBlank(orderBy)){
            if (Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                String[] orderByArray = orderBy.split("_");
                PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
            }
        }

        keyword = StringUtils.isBlank(keyword) ? null : keyword;
        List<Product> productList = productMapper.selectByNameAndCategoryIds(keyword,
                categoryList.size() == 0 ? null : categoryList);

        List<ProductListVo> productListVoList = Lists.newArrayList();
        for (Product product : productList){
            ProductListVo productListVo = assembleProductListVo(product);
            productListVoList.add(productListVo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }


}
View Code

六、Controller层:

后台:

package com.mmall.controller.backend;

import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.Product;
import com.mmall.pojo.User;
import com.mmall.service.IFileService;
import com.mmall.service.IProductService;
import com.mmall.service.IUserService;
import com.mmall.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.util.Map;

import static com.mmall.common.Const.CURRENT_USER;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/10.
 */
@Controller
@RequestMapping("/manage/product")
public class ProductManageController {

    @Autowired
    IUserService iUserService;
    @Autowired
    IProductService iProductService;
    @Autowired
    IFileService iFileService;

    /**
     * 新增或更新产品
     * @param session
     * @param product
     * @return
     */
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse saveOrUpdateProduct(HttpSession session, Product product){
        User user = (User) session.getAttribute(CURRENT_USER);
        if (user == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录");
        }
        ServerResponse<String> response = iUserService.checkAdminRole(user);
        if (!response.isSuccess()){
            return response;
        }else {
            return iProductService.saveOrUpdateProduct(product);
        }

    }


    /**
     * 产品上下架 status:1-在售 2-下架 3-删除
     * @param session
     * @param productId
     * @param status
     * @return
     */
    @RequestMapping(value = "/set_sale_status", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse updateSaleStatus(HttpSession session,
                                           @RequestParam("productId") Integer productId,
                                           @RequestParam("status") Integer status){
        User user = (User) session.getAttribute(CURRENT_USER);
        if (user == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录");
        }
        ServerResponse<String> response = iUserService.checkAdminRole(user);
        if (!response.isSuccess()){
            return response;
        }else {
            return iProductService.updateProductStatus(productId, status);
        }

    }

    /**
     * 获取产品详情
     * @param session
     * @param productId
     * @return
     */
    @RequestMapping(value = "/detail.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getProductDetail(HttpSession session, Integer productId){
        User user = (User) session.getAttribute(CURRENT_USER);
        if (user == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录");
        }
        ServerResponse<String> response = iUserService.checkAdminRole(user);
        if (!response.isSuccess()){
            return response;
        }else {
            return iProductService.manageGetProductDetail(productId);
        }
    }

    /**
     * 查询大量商品页,分页查询
     * @param session
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getProductList(HttpSession session,
                                         @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") int pageSize){
        User user = (User) session.getAttribute(CURRENT_USER);
        if (user == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录");
        }
        ServerResponse<String> response = iUserService.checkAdminRole(user);
        if (!response.isSuccess()){
            return response;
        }else {
            return iProductService.manageGetProductList(pageNum, pageSize);
        }
    }

    /**
     * 模糊查询符合条件的商品详情
     * @param session
     * @param productName
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/search.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse searchProduct(HttpSession session,
                                        @RequestParam("productName") String productName,
                                        @RequestParam("productId") Integer productId,
                                        @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10") int pageSize){

        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录");
        }
        ServerResponse<String> response = iUserService.checkAdminRole(user);
        if (!response.isSuccess()){
            return response;
        }else {
            return iProductService.searchProduct(productName, productId, pageNum, pageSize);
        }
    }

    /**
     * 上传文件
     * @param session
     * @param request
     * @param uploadFile
     * @return
     */
    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse upload(HttpSession session,
                                 HttpServletRequest request,
                                 @RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null){
            return ServerResponse.createByErrorCodeMsg(ResponseCode.NEED_LOGIN.getCode(), "未登录,请先登录");
        }
        ServerResponse<String> response = iUserService.checkAdminRole(user);

        if (!response.isSuccess()){
            return response;
        }else {
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(uploadFile, path);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;

            Map fileMap = Maps.newHashMap();
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);
            return ServerResponse.createBySuccess(fileMap);
        }


    }


    /**
     * 上传富文本
     * @param session
     * @param uploadFile
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/richtext_img_upload.do", method = RequestMethod.POST)
    @ResponseBody
    public Map richtextImgUpload(HttpSession session,
                                            @RequestParam("uploadFile") MultipartFile uploadFile,
                                            HttpServletRequest request,
                                            HttpServletResponse response){

        Map resultMap = Maps.newHashMap();
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null){
            resultMap.put("success", false);
            resultMap.put("msg", "未登录,请先登录");
            return resultMap;
        }
        //富文本中对于返回值有自己的要求,我们使用是simditor所以按照simditor的要求进行返回
//        {
//            "success": true/false,
//                "msg": "error message", # optional
//            "file_path": "[real file path]"
//        }
        ServerResponse<String> serverResponse = iUserService.checkAdminRole(user);
        if (!serverResponse.isSuccess()){
            resultMap.put("success", false);
            resultMap.put("msg", serverResponse.getMsg());
            return resultMap;
        }else {
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(uploadFile, path);
            if (StringUtils.isNotBlank(targetFileName)){
                String url = PropertiesUtil.getProperty("") + targetFileName;
                resultMap.put("success", true);
                resultMap.put("msg", "上传成功");
                resultMap.put("file_path", url);
                response.addHeader("Access-Control-Allow-Headers","X-File-Name");
                return resultMap;
            }else {
                resultMap.put("success", false);
                resultMap.put("msg", "上传失败");
                return resultMap;
            }
        }





    }




}
View Code

门户前台:

package com.mmall.controller.portal;

import com.mmall.common.ServerResponse;
import com.mmall.service.IProductService;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/12.
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    IProductService iProductService;


    /**
     * 根据产品productId返回对应的产品详情
     * @param productId
     * @return
     */
    @RequestMapping(value = "/detail.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getProdutcDetail(Integer productId){
        return iProductService.getProductDetail(productId);
    }

    /**
     * 根据品类id查找该品类下所有产品详情或者根据产品名称关键字进行模糊查询
     * @param categoryId
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @param orderBy
     * @return
     */
    @RequestMapping(value = "/list.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getProductList(@RequestParam(value = "categoryId", required = false) Integer categoryId,
                                         @RequestParam(value = "keyword", required = false) String keyword,
                                         @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                         @RequestParam(value = "orderBy", defaultValue = "") String orderBy){
        return iProductService.getProductList(categoryId, keyword, pageNum, pageSize, orderBy);
    }


}
View Code

七、POJO层:

package com.mmall.pojo;

import java.math.BigDecimal;
import java.util.Date;

public class Product {
    private Integer id;

    private Integer categoryId;

    private String name;

    private String subtitle;

    private String mainImage;

    private String subImages;

    private String detail;

    private BigDecimal price;

    private Integer stock;

    private Integer status;

    private Date createTime;

    private Date updateTime;

    public Product(Integer id, Integer categoryId, String name, String subtitle, String mainImage, String subImages, String detail, BigDecimal price, Integer stock, Integer status, Date createTime, Date updateTime) {
        this.id = id;
        this.categoryId = categoryId;
        this.name = name;
        this.subtitle = subtitle;
        this.mainImage = mainImage;
        this.subImages = subImages;
        this.detail = detail;
        this.price = price;
        this.stock = stock;
        this.status = status;
        this.createTime = createTime;
        this.updateTime = updateTime;
    }

    public Product() {
        super();
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle == null ? null : subtitle.trim();
    }

    public String getMainImage() {
        return mainImage;
    }

    public void setMainImage(String mainImage) {
        this.mainImage = mainImage == null ? null : mainImage.trim();
    }

    public String getSubImages() {
        return subImages;
    }

    public void setSubImages(String subImages) {
        this.subImages = subImages == null ? null : subImages.trim();
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail == null ? null : detail.trim();
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Integer getStock() {
        return stock;
    }

    public void setStock(Integer stock) {
        this.stock = stock;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}
View Code

VO层:

package com.mmall.vo;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/10.
 */
public class ProductDetailVo {
    private Integer id;

    private Integer categoryId;

    private String name;

    private String subtitle;

    private String mainImage;

    private String subImages;

    private String detail;

    private BigDecimal price;

    private Integer stock;

    private Integer status;

    private String createTime;

    private String updateTime;

    //图片服务器URL前缀
    private String imageHost;
    //父分类
    private Integer parentCategoryId;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSubtitle() {
        return subtitle;
    }

    public void setSubtitle(String subtitle) {
        this.subtitle = subtitle;
    }

    public String getMainImage() {
        return mainImage;
    }

    public void setMainImage(String mainImage) {
        this.mainImage = mainImage;
    }

    public String getSubImages() {
        return subImages;
    }

    public void setSubImages(String subImages) {
        this.subImages = subImages;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public Integer getStock() {
        return stock;
    }

    public void setStock(Integer stock) {
        this.stock = stock;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(String updateTime) {
        this.updateTime = updateTime;
    }

    public String getImageHost() {
        return imageHost;
    }

    public void setImageHost(String imageHost) {
        this.imageHost = imageHost;
    }

    public Integer getParentCategoryId() {
        return parentCategoryId;
    }

    public void setParentCategoryId(Integer parentCategoryId) {
        this.parentCategoryId = parentCategoryId;
    }
}
View Code
package com.mmall.vo;

import java.math.BigDecimal;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/10.
 */
public class ProductListVo {
    private Integer id;
    private Integer categoryId;
    private String name;
    private String mainImage;
    private Integer status;
    private BigDecimal price;
    private String subTitle;
    private String imageHost;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(Integer categoryId) {
        this.categoryId = categoryId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMainImage() {
        return mainImage;
    }

    public void setMainImage(String mainImage) {
        this.mainImage = mainImage;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getImageHost() {
        return imageHost;
    }

    public void setImageHost(String imageHost) {
        this.imageHost = imageHost;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }
}
View Code

八、Util层:

DateTimeUtil.java:

package com.mmall.util;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.Date;


/**
 * @author GenshenWang.nomico
 * @date 2018/4/10.
 */
public class DateTimeUtil {

    private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";

    //str > date
    public static Date strToDate(String dateTimeStr){
        DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(STANDARD_FORMAT);
        DateTime dateTime = dateTimeFormat.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }

    public static Date strToDate(String dateTimeStr, String formatStr){
        DateTimeFormatter dateTimeFormat = DateTimeFormat.forPattern(formatStr);
        DateTime dateTime = dateTimeFormat.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }

    //date > str
    public static String dateToStr(Date date){
        if (date == null){
            return null;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(STANDARD_FORMAT);
    }

    public static String dateToStr(Date date, String formatStr){
        if (date == null){
            return null;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(formatStr);
    }

}
View Code

FTPUtill.java:

package com.mmall.util;

import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/11.
 */
public class FTPUtill {

    private static final Logger logger = LoggerFactory.getLogger(FTPUtill.class);

    //todo FTP服务器未配置
    private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
    private static int ftpPort = 21;
    private static String ftpUser = PropertiesUtil.getProperty("mmallftp");
    private static String ftpPass = PropertiesUtil.getProperty("ftppassword");

    private String ip;
    private int port;
    private String user;
    private String pwd;
    private FTPClient ftpClient;

    public static Logger getLogger() {
        return logger;
    }

    public static String getFtpIp() {
        return ftpIp;
    }

    public static void setFtpIp(String ftpIp) {
        FTPUtill.ftpIp = ftpIp;
    }

    public static int getFtpPort() {
        return ftpPort;
    }

    public static void setFtpPort(int ftpPort) {
        FTPUtill.ftpPort = ftpPort;
    }

    public static String getFtpUser() {
        return ftpUser;
    }

    public static void setFtpUser(String ftpUser) {
        FTPUtill.ftpUser = ftpUser;
    }

    public static String getFtpPass() {
        return ftpPass;
    }

    public static void setFtpPass(String ftpPass) {
        FTPUtill.ftpPass = ftpPass;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }

    public FTPUtill(String ip, int port, String user, String pass){
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.pwd = pass;
    }

    private boolean connectFTPServer(String ip, int port, String user, String pass){
        boolean connectSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            connectSuccess = ftpClient.login(user, pass);
        } catch (IOException e) {
            logger.error("连接FTP服务器异常", e);
        }
        return connectSuccess;
    }

    public static boolean uploadFile(List<File> fileList){
        FTPUtill ftpUtill = new FTPUtill(ftpIp, ftpPort, ftpUser, ftpPass);
        logger.info("开始连接ftp服务器");
        boolean result = ftpUtill.uploadFile("img", fileList);
        logger.info("结束上传,上传结果:{}");
        return result;
    }

    private boolean uploadFile(String remotePath, List<File> fileList){
        boolean uploaded = true;
        FileInputStream fis = null;
        boolean isConnectSuccess = connectFTPServer(this.ip, this.port, this.user, this.pwd);
        if (isConnectSuccess){
            try {
                ftpClient.changeWorkingDirectory(remotePath);
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                for (File file : fileList){
                    fis = new FileInputStream(file);
                    ftpClient.storeFile(file.getName(), fis);
                }
            } catch (IOException e) {
                logger.error("上传文件异常", e);
                uploaded = false;
            }

        }

        return uploaded;
















    }







}
View Code

PropertiesUtil.java:

package com.mmall.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Created by geely
 */
public class PropertiesUtil {

    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Properties props = null;

    static {
        String fileName = "mmall.properties";
        props = new Properties();
        try {
            props.load(new InputStreamReader(PropertiesUtil.class.getResourceAsStream(fileName)));
        } catch (IOException e) {
            logger.error("配置文件读取异常", e);
        }
    }

    public static String getProperty(String key){
        String value = props.getProperty(key);
        if (value == null){
            return null;
        }
        return value.trim();
    }

    public static String getProperty(String key, String defaultValue){
        String value = props.getProperty(key);
        if (value == null){
            return defaultValue;
        }
        return value.trim();
    }

}
View Code

九、Common层

Const.java

package com.mmall.common;

import com.google.common.collect.Sets;

import java.util.Set;

/**
 * @author GenshenWang.nomico
 * @date 2018/4/5.
 */
public class Const {

    public static final String CURRENT_USER = "currentUser";
    public static final String EMAIL = "email";
    public static final String USERNAME = "username";

    public interface Role{
        int ROLE_CUSTOMER = 0; //普通用户
        int ROLE_ADMIN = 1;//管理员
    }

    public enum ProductStatusEnum {

        ON_SALE(1, "在售");
        private int code;
        private String desc;
        ProductStatusEnum(int code, String desc){
            this.code = code;
            this.desc = desc;
        }

        public int getCode() {
            return code;
        }

        public String getDesc() {
            return desc;
        }
    }

    public interface ProductListOrderBy{
        //Set查询效率为O(1), List为O(n)
        Set<String> PRICE_ASC_DESC = Sets.newHashSet("price_desc","price_asc");
    }

}
View Code

十、FTP配置文件

mmall.properties

ftp.server.ip=你的FTP服务器ip地址
ftp.user=geely
ftp.pass=geely
ftp.server.http.prefix=http://img.happymmall.com/
View Code

 

posted on 2018-04-12 22:07  noaman_wgs  阅读(1523)  评论(0编辑  收藏  举报