智能商贸-day9-产品模块

1.1. 展示产品页面代码

1.1.1. product.jsp

<table id="productGrid" class="easyui-datagrid" data-options="fit:true,fixed:true,fitColumns:true,toolbar:'#tb',singleSelect:true";
       url="/product/page"
       iconCls="icon-save"
       rownumbers="true" pagination="true">
    <thead>
    <tr>
        <th width="20"  field="name"  >名称</th>
        <th width="20"  field="color"  data-options="formatter:formatColor"  >颜色</th>
        <th width="20"  field="smallpic"  data-options="formatter:formatImg"  >图片</th>
        <th width="20"  field="costprice"  >成本价</th>
        <th width="20"  field="saleprice"  >销售价</th>
        <th width="20"  field="types"  data-options="formatter:formatObj"  >类型</th>
        <th width="20"  field="unit"  data-options="formatter:formatObj" >单位</th>
        <th width="20"  field="brand"  data-options="formatter:formatObj" >品牌</th>
    </tr>
    </thead>
</table>

1.1.2. product.js

function formatImg(data) {
    return "<img src='"+data+"' alt='没有图片' />"
}
function formatColor(data) {
    return "<div style='width: 20px;height: 20px;background-color: "+data+"'></div>"
}
function formatObj(data) {
    if(data){
        return data.name;
    }
}

1.2. 大图展示

引入支持的js文件

<script type="text/javascript" src="/easyui/plugin/tooltip/jeasyui.extensions.base.tooltip.js"></script>

注册加载完毕事件

<table id="productGrid" class="easyui-datagrid"
       data-options="fit:true,fixed:true,fitColumns:true,toolbar:'#tb',singleSelect:true,onRowContextMenu:showMenu,onLoadSuccess:loadSuccess"
       url="/product/page"
       iconCls="icon-save"
       enableHeaderClickMenu="true"
       rownumbers="true" pagination="true"
>
。。。。  
</table>

准备loadSuccess方法:

//成功后进行加载
function loadSuccess(data) {
    var rows = data.rows;
   for(var i=0;i<rows.length;i++){
       var result = rows[i];
       $.easyui.tooltip.init($("img[src='"+result.smallpic+"']"), {
           position: "rigth",
           content: "<div style=\"width:600px;height:480px;\"><img src='"+result.pic+"'  /></div>"
       });
   }
}

1.3. 添加与修改页面

1.3.1. product.jsp

颜色选择可以找一些其它的控件:

<div id="productDialog" class="easyui-dialog" data-options="closed:true,modal:true" title="功能操作" style="width:450px">
    <div style="padding:10px 60px 20px 40px">
        <form id="productForm" class="easyui-form" method="post" data-options="">
            <input type="hidden" id="productId" name="id" >
            <table cellpadding="5">
                <tr>
                    <td>名称:</td>
                    <td><input class="easyui-validatebox" type="text" name="name" data-options="required:true"></input></td>
                </tr>
                <tr>
                    <td>颜色:</td>
                    <td><input class="easyui-validatebox" type="color" name="color"></input></td>
                </tr>
                <tr>
                    <td>成本价:</td>
                    <td><input class="easyui-validatebox" type="text" name="costprice"></input></td>
                </tr>
                <tr>
                    <td>销售价:</td>
                    <td><input class="easyui-validatebox" type="text" name="saleprice"></input></td>
                </tr>
                <tr>
                    <td>产品图片:</td>
                    <td>
                        <input name="fileImage" class="easyui-filebox" style="width:100%">
                    </td>
                </tr>
            </table>
        </form>
        <div style="text-align:center;padding:5px">
            <a href="javascript:void(0)" class="easyui-linkbutton" data-method="save">提交</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#productDialog').dialog('close')">取消</a>
        </div>
    </div>
</div>

1.3.2. 品牌与单位的读取展示

这两个数据我们直接从数据字典中获取即可:

SystemdictionarydetailRepository
public interface SystemdictionarydetailRepository extends BaseRepository<Systemdictionarydetail,Long> {
    //根据类型拿到相应的数据
    @Query("select o from Systemdictionarydetail o where o.types.sn = ?1")
    List<Systemdictionarydetail> findAllBySn(String sn);
}

SystemdictionarydetailServiceImpl
@Service
public class SystemdictionarydetailServiceImpl extends BaseServiceImpl<Systemdictionarydetail,Long> implements ISystemdictionarydetailService {

    @Autowired
    public SystemdictionarydetailRepository systemdictionarydetailRepository;

    @Override
    public List<Systemdictionarydetail> findAllUnit() {
        return systemdictionarydetailRepository.findAllBySn(Systemdictionarytype.PRODUCT_UNIT);
    }

    @Override
    public List<Systemdictionarydetail> findAllBrand() {
        return systemdictionarydetailRepository.findAllBySn(Systemdictionarytype.PRODUCT_BRAND);
    }
}

UtilController
//拿到所有品牌
@RequestMapping("/findAllBrand")
@ResponseBody
public List<Systemdictionarydetail> findAllBrand(){
    return systemdictionarydetailService.findAllBrand();
}

//拿到所有单位
@RequestMapping("/findAllUnit")
@ResponseBody
public List<Systemdictionarydetail> findAllUnit(){
    return systemdictionarydetailService.findAllUnit();
}

product.jsp
<tr>
    <td>单位:</td>
    <td>
        <input  class="easyui-combobox" name="unit.id"
                data-options="valueField:'id',textField:'name',panelHeight:'auto',url:'/util/findAllUnit'">
    </td>
</tr>
<tr>
    <td>品牌:</td>
    <td>
        <input  class="easyui-combobox" name="brand.id"
                data-options="valueField:'id',textField:'name',panelHeight:'auto',url:'/util/findAllBrand'">
    </td>
</tr>          

产品类型读取展示

Producttype

public String getGroup(){
    if(parent!=null){
        return parent.getName();
    }
    return "";
}

ProducttypeRepository

public interface ProducttypeRepository extends BaseRepository<Producttype,Long> {
    //拿到所有子类型
@Query("select o from Producttype o where o.parent.id is not null")
List<Producttype> findChildren();
}
Controller与Service省略,和以前一样调用即可!!

product.jsp

<tr>
    <td>类型:</td>
    <td>

        <input  class="easyui-combobox" name="types.id"
                data-options="groupField:'group',valueField:'id',textField:'name',panelHeight:'auto',url:'/util/findChildren'">
    </td>
</tr>

1.3.4. 产品修改时回显

product.js

//修改数据(弹出修改的模态框)
edit:function () {
    //选中了某一条数据才删除
    var row = productGrid.datagrid("getSelected");
    if(row){
        //隐藏有data-save属性的元素
        $("*[data-save]").hide();
        //禁用有data-save属性的input元素的验证功能
        $("*[data-save] input").validatebox("disableValidation");

        productForm.form("clear");//清除数据
        productDialog.dialog("center").dialog('open');
        //解决单位,品牌,类型的回显问题
        if(row.unit){
            row["unit.id"] = row.unit.id;
        }
        if(row.brand){
            row["brand.id"] = row.brand.id;
        }
        if(row.types){
            row["types.id"] = row.types.id;
        }
        //为form加载数据
        productForm.form("load",row);
    }else{
        $.messager.alert('提示信息','请选择一行再进行修改!','info');
    }
},

1.4. 添加与修改后台

ProductController中进行接收并保存:

@Controller
@RequestMapping("/product")
public class ProductController extends BaseController  {
//图片上传功能
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmssS");
//图片上传功能
public void uploadImage(Product product, MultipartFile fileImage, HttpServletRequest req){
    if(fileImage!=null) {
        String webapp = req.getServletContext().getRealPath("/");
        //图片存在就把它给删除掉
    /*
    if (product.getId() != null && StringUtils.isNotBlank(product.getPic())) {
        File deleteFile = new File(webapp, product.getPic());
        if (deleteFile.exists()) {
            deleteFile.delete();
        }
        File deleteFile2 = new File(webapp, product.getSmallPic());
        if (deleteFile2.exists()) {
            deleteFile2.delete();
        }
    }
   */
        try {
            // 上传文件命名,拷贝到webapp的位置,设置pic到product
            Date date = new Date();
            // 大小图的路径+文件名称
            String fileName = "/upload/" + sdf.format(date) + ".png";
            String smallFileName = "/upload/" + sdf.format(date) + "_small.png";
            // 大小图的在服务器上面的物理路径
            File destFile = new File(webapp, fileName);
            File smallDestFile = new File(webapp, smallFileName);

            // 生成upload目录
            File parentFile = destFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();// 自动生成upload目录
            }

            // 把上传的临时图片,复制到当前项目的webapp路径
            //FileUtils.copyFile(upload, destFile);
            FileCopyUtils.copy(fileImage.getInputStream(), new FileOutputStream(destFile));
            // 处理缩略图
            //Thumbnails.of(upload).scale(0.1F).toFile(smallDestFile);
            Thumbnails.of(fileImage.getInputStream()).scale(0.1F).toFile(smallDestFile);
            // 把大小图的相对webapp的路径设置到数据库产品表里面
            product.setPic(fileName);
            product.setSmallpic(smallFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
//添加
@RequestMapping("/save")
@ResponseBody
public Map<String,Object> save(Product product,HttpServletRequest req){
    return saveOrUpdate(product,req);
}

//修改
@RequestMapping("/update")
@ResponseBody
public Map<String,Object> update(@ModelAttribute("editProduct")Product product, HttpServletRequest req){
    return saveOrUpdate(product,req);
}

//添加或者修改
private Map<String,Object> saveOrUpdate(Product product, HttpServletRequest req){
    //下面是解决上传文件为空报错的问题
    MultipartFile fileImage = null;
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (isMultipart){
        MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(req, MultipartHttpServletRequest.class);
        fileImage = multipartRequest.getFile("fileImage");
    }
    uploadImage(product, fileImage, req);

    Map<String,Object> map = new HashMap<>();
    try {
        productService.save(product);
        map.put(SUCCESS, true);
    } catch (Exception e) {
        e.printStackTrace();
        map.put(SUCCESS, false);
        map.put("msg", e.getMessage());
    }
    return map;
}

}

1.5. 修改时注意

/**
 * @param cmd:只有这个cmd为update的时候,才执行功能
 */
@ModelAttribute("editProduct")
public Product beforeEdit(Long id,String cmd){
    if(id!=null && "update".equals(cmd)){
        Product product = productService.findOne(id);
        //把有关系的对象移除
        product.setBrand(null);
        product.setUnit(null);
        product.setTypes(null);
        return product;
    }
    return null;
}

1.6.	删除产品同时删除图片
//删除功能
@RequestMapping("/delete")
@ResponseBody
public Map<String,Object> delete(Long id,HttpServletRequest req){
    Map<String,Object> map = new HashMap<>();
    try{
        Product product = productService.findOne(id);
        productService.delete(id);
        // 删除图片的代码,写在delete方法之后
        String webapp = req.getServletContext().getRealPath("/");
        if (id != null && StringUtils.isNotBlank(product.getPic())) {
            File deleteFile = new File(webapp, product.getPic());
            if (deleteFile.exists()) {
                deleteFile.delete();
            }
            File deleteSmallFile = new File(webapp, product.getSmallPic());
            if (deleteSmallFile.exists()) {
                deleteSmallFile.delete();
            }
        }
        map.put(SUCCESS,true);
    }catch (Exception e){
        map.put(SUCCESS,false);
        map.put("msg",e.getMessage());
        e.printStackTrace();
    }
    return map;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值