精华内容
下载资源
问答
  • SpringBoot + Layui后台管理系统 重点: SpringBoot 2.1.0 tk.mybatis 2.0.2 四郎1.3.1 Lombok1.18.4 前置: 拉伊2.4.5 jQuery的3.3.1 渲染模板 胸腺
  • 基于springboot+mybatis+layui实现网上购物商城,含有支付功能。
  • market-goods_springboot_springbootlayui_boymhz.zip
  • market-goods_springboot_springbootlayui_boymhz_源码.rar
  • 前端 cateTree.html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head th:include="layout...link rel="stylesheet" th:href="@{/layui/css/layui.css}"></link> <scrip
    前端 cateTree.html
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org"> 
    <head th:include="layout :: htmlhead" th:with="title='角色管理'"></head>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}"></link>
    <script th:src="@{/layui/layui.js}"></script> 
    <body class="layui-layout-body">
    <div class="layui-layout layui-layout-admin">
        <div class="layui-body" style="margin: 1%">
    
            <div id="test13" class="demo-tree-more"></div>
         </div>
        <script th:src="@{/js/myTree.js}"></script>
    </div>
    </body>
    </html>
    
    前端 myTree.js
    $(function() {
    	getData();
    })
    function getData(){ 
        $.ajax({
            type: "get",
            data: "id=0",
            url: "/category/findCategoryJson",
            success: function (data) {
                layui.use(['tree', 'util'], function() {
                    var tree = layui.tree
                        , layer = layui.layer
                        , util = layui.util
                    //无连接线风格
                    tree.render({
                        elem: '#test13'
                        ,data: data
                         ,showLine: false  //是否开启连接线
                    });
                }) 
            }, 
        });
    }
    
    Controller中的方法
     @RequestMapping(value = "/findCategoryJson")
        @ResponseBody
        public List<TreeNode> findTree(){
            List<TreeNode> list=categoryService.getTree();
            return list;
        }
    
    service中的方法
    List<TreeNode> getTree();
    
    serviceImpl中的方法
      @Override
        public List<TreeNode> getTree() {
            BuildTree buildTree=new BuildTree();
            //获取数据的list
            List<TreeNode> treeNodes=categoryDOMapper.selectTree();
            List<TreeNode> list= buildTree.buildTree(treeNodes);
            return list;
        }
    
    dao中
      List<TreeNode> selectTree();
    
    Treemapper.xml
     <select id="selectTree" resultType="com.kcmm.shops.common.tree.TreeNode">
        SELECT id AS id,category_name AS title , parent_id AS pid FROM category
      </select>
    
    BuildTree 类
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Created by fengcai on 2020/7/5.
     */
    public class BuildTree {
    
        List<TreeNode> TreeNodes = new ArrayList<>();
        public List<TreeNode> buildTree(List<TreeNode> TreeNodes) {
            BuildTree treeBuilder = new BuildTree(TreeNodes);
            return treeBuilder.buildJSONTree();
        }
    
        public BuildTree() {
        }
    
        public BuildTree(List<TreeNode> TreeNodes) {
            super();
            this.TreeNodes = TreeNodes;
        }
    
        // 构建JSON树形结构
        public List<TreeNode> buildJSONTree() {
            List<TreeNode> TreeNodeTree = buildTree();
            return TreeNodeTree;
        }
    
        // 构建树形结构
        public List<TreeNode> buildTree() {
            List<TreeNode> treeTreeNodes = new ArrayList<>();
            //获取所有根节点
            List<TreeNode> rootTreeNodes = getRootTreeNodes();
            //获取每个根节点
            for (TreeNode rootTreeNode : rootTreeNodes) {
                try {
                    //递归这个根节点的子节点
                    buildChildTreeNodes(rootTreeNode);
    
                    //用list来存放每个根节点
                    treeTreeNodes.add(rootTreeNode);
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
            }
            return treeTreeNodes;
        }
    
        // 递归子节点
        public void buildChildTreeNodes(TreeNode TreeNode) {
            List<TreeNode> children = getChildTreeNodes(TreeNode);
            if (!children.isEmpty()) {
                for (TreeNode child : children)
                    try {
                        buildChildTreeNodes(child);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                TreeNode.setChildren(children);
            }
        }
    
        /**
         * 获取父节点下所有的子节点
         * @param pTreeNode
         * @return
         */
        public List<TreeNode> getChildTreeNodes(TreeNode pTreeNode) {
            List<TreeNode> childTreeNodes = new ArrayList<>();
    
            for (TreeNode n : TreeNodes) {
              //  if (pTreeNode.getCode().equals(n.getPcode())) {
                if (pTreeNode.getId().equals(n.getPid())) {
                    childTreeNodes.add(n);
                }
            }
            return childTreeNodes;
        }
    
        // 判断是否为根节点
        public boolean rootTreeNode(TreeNode TreeNode) {
            boolean isRootTreeNode = true;
            for (TreeNode n : TreeNodes) {
               // if (TreeNode.getPcode().equals(n.getCode())) {
                if (TreeNode.getPid().equals(n.getId())) {
                    isRootTreeNode = false;
                    break;
                }
            }
            return isRootTreeNode;
        }
    
        // 获取集合中所有的根节点
        public List<TreeNode> getRootTreeNodes() {
            List<TreeNode> rootTreeNodes = new ArrayList<>();
            for (TreeNode n : TreeNodes) {
                if (rootTreeNode(n)) {
                    rootTreeNodes.add(n);
                }
            }
            return rootTreeNodes;
        }
    }
    

    TreeNode 类

    
    public class TreeNode  {
    
        private Integer id;
        private Integer cid;
    
        private String title;
    
        private Integer pid;
    
        private List<TreeNode> children = new ArrayList();
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public Integer getCid() {
            return cid;
        }
    
        public void setCid(Integer cid) {
            this.cid = cid;
        }
    
      /*  public String getCname() {
            return cname;
        }
    
        public void setCname(String cname) {
            this.cname = cname;
        }*/
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public Integer getPid() {
            return pid;
        }
    
        public void setPid(Integer pid) {
            this.pid = pid;
        }
    
        public List getChildren() {
            return children;
        }
    
        public void setChildren(List children) {
            this.children = children;
        }
    
        @Override
        public String toString() {
            return "TreeNode{" +
                    "id=" + id +
                    //", cname='" + cname + '\'' +
                    ", title='" + title + '\'' +
                    ", pid=" + pid +
                    ", children=" + children +
                    '}';
        }
    }
    

    效果图
    在这里插入图片描述

    展开全文
  • springboot+layui实现数据表格功能,提供增删改查模糊搜索功能,含有项目解析以及sql文件,具有echart图表功能,是一个功能齐全的后台管理系统模板。
  • idea开发工具,使用了mybatis generator插件和lombook插件,maven导入依赖后,安装lombook或者自己封装即可。有问题请私信
  • layui-form-item layui-form-text " style =" margin-top : 50px " > < label for = " content " class = " layui-form-label " style =" width : 80px ; " > 项目内容: label > < div class = ...

    ajax-form提交

    前端代码:

    <!DOCTYPE HTML>
    <html  xmlns:th="http://www.thymeleaf.org">
    <head th:include="_meta :: header">
        <title>添加</title>
    
    </head>
    <link rel="stylesheet" th:href="@{/xadmin/lib/formselect/formSelects-v4.css}">
    <body>
    <div class="layui-fluid">
        <div class="layui-row">
            <form class="layui-form form form-horizontal" id="form-materialMart-add" action="#" th:action="@{/admin/materialMart/edit}"
                  th:object="${materialMart}" enctype="multipart/form-data">
                <input type="hidden" name="id" th:value="${materialMart.id}"/>
                <input type="hidden" id="checked" th:value="${materialProjects}"/>
                <div class="layui-form-item">
                    <label class="layui-form-label">项目类型:</label>
                    <div class="layui-input-block">
                        <select name="typeId" id="type" xm-select="select9" xm-select-search xm-select-create>
                            <option name="rights" th:each="recommendMenuSecond:${recommendMenuSeconds}" th:text="${recommendMenuSecond.menuName}" th:title="${recommendMenuSecond.menuName}" th:value="${recommendMenuSecond.id}"></option>
                        </select>
                    </div>
                </div>
    
                <div class="layui-form-item" style="margin-top: 50px">
                    <label class="layui-form-label" style="width:80px;">项目标题:</label>
                    <div class="layui-input-inline">
                        <input type="layui-input" class="layui-input" style="width: 738px;" th:value="${materialMart.title}"  name="title"  placeholder="添加项目标题" id="title"/>
                    </div>
                </div>
    <!--            <div class="layui-form-item">-->
    <!--                <label class="layui-form-label" style="width:80px;">上传图标:</label>-->
    <!--                <div class="layui-input-inline">-->
    <!--                    <input type="file" class="layui-input" th:value="${materialMart.Icon}" name="imageFile" multiple placeholder="添加项目图标" id="Icon"/>-->
    <!--                </div>-->
    <!--            </div>-->
    
                <div class="layui-form-item" style="margin-top: 50px">
                    <label class="layui-form-label">项目图标:</label>
                    <div class="imgcon" style="float: left">
                    </div>
                    <input type="hidden" value="" name="Icon"  class="goods_img">
                    <div class="addimg" style="float: left">
                        <div id="drag" class="" title="将文件拖拽到此处上传">
                            <label for="fileupload" title="点击上传">
                                <img th:src="${materialMart.Icon}" style="height: 100px;width: 100px;" alt="">
                            </label>
                        </div>
                        <input style="display: none" id="fileupload" type="file" accept="image/*" name="imageFile"
                               multiple="multiple" data-url="/admin/materialMart/addFile">
                    </div>
                </div>
    
                <!--                <div class="layui-form-item">-->
                <!--                    <label class="layui-form-label"><span-->
                <!--                            class="c-red">* </span>项目内容:</label>-->
                <!--                    <div class="layui-input-block">-->
                <!--                        <script id="editor" th:text="${materialMart.content}" name="content" autofocus type="text/plain" style="height: 500px">-->
                <!--                        </script>-->
                <!--                    </div>-->
                <!--                </div>-->
                <div class="layui-form-item layui-form-text" style="margin-top: 50px">
                    <label for="introduction" class="layui-form-label" style="width:80px;">项目简介:</label>
                    <div class="layui-input-block">
                        <textarea id="introduction" name="introduction" th:text="${materialMart.introduction}" class="layui-textarea" style="width:900px;height:200px;margin-right:20px;"></textarea>
                    </div>
                </div>
                <div class="layui-form-item layui-form-text" style="margin-top: 50px">
                    <label for="content" class="layui-form-label" style="width:80px;">项目内容:</label>
                    <div class="layui-input-block">
                        <textarea id="content" name="content" th:text="${materialMart.content}" class="layui-textarea" style="width:900px;height:400px;margin-right:20px;"></textarea>
                    </div>
                </div>
                <div class="layui-form-item" style="margin-top: 50px">
                    <label class="layui-form-label" style="width:80px;">项目价格:</label>
                    <div class="layui-input-inline">
                        <input type="layui-input" class="layui-input" th:value="${materialMart.price}" name="price"  placeholder="添加项目价格" id="price"/>
                    </div>
                </div>
                <div class="layui-form-item" style="margin-top: 50px">
                    <label class="layui-form-label" style="width:80px;">咨询电话:</label>
                    <div class="layui-input-inline">
                        <input type="layui-input" class="layui-input" th:value="${materialMart.phoneNumber}"  name="phoneNumber"  placeholder="添加咨询电话" id="phoneNumber"/>
                    </div>
                </div>
    
                <div class="layui-form-item" style="margin-top: 50px">
                    <label class="layui-form-label" style="width:80px;">是否精选:</label>
                    <div class="layui-input-block" style="width: 200px">
                        <select name="isGoods" id="isGoods">
                            <option th:value="${materialMart.isGoods}"></option>
                            <option th:text="" th:value="1"></option>
                            <option th:text="" th:value="0"></option>
                        </select>
                    </div>
                </div>
    
                <div class="layui-form-item" style="margin-top: 50px;margin-bottom: 60px;">
                    <label class="layui-form-label">
                    </label>
                    <button  class="layui-btn" id="subbtn" type="submit" >
                        修改
                    </button>
                    <button  class="layui-btn" id="reset" type="reset" >
                        重置
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!--_footer 作为公共模版分离出去-->
    <div th:replace="_footer :: footerjs"></div>
    <!--<div th:replace="_ueditor :: ueditor"></div>-->
    <script th:src="@{/xadmin/lib/formselect/formSelects-v4.js}" charset="utf-8"></script>
    <!--/_footer 作为公共模版分离出去-->
    <!--请在下方写此页面业务相关的脚本-->
    <link rel="stylesheet" type="text/css" th:href="@{/xadmin/lib/formSelect/formSelects-v4.css}"/>
    <script type="text/javascript" th:src="@{/xadmin/lib/formselect/formSelects-v4.js}"></script>
    <script th:src="@{/xadmin/lib/jQuery-File-Upload/js/vendor/jquery.ui.widget.js}"></script>
    <script th:src="@{/xadmin/lib/jQuery-File-Upload/js/jquery.iframe-transport.js}"></script>
    <script th:src="@{/xadmin/lib/jQuery-File-Upload/js/jquery.fileupload.js}"></script>
    <script>
        layui.use(['form', 'layer','laydate'],function() {
            $ = layui.jquery;
            var form = layui.form,
                laydate = layui.laydate,
                layer = layui.layer;
            lay('.timeSpace').each(function(){
                laydate.render({
                    elem: this
                    ,trigger: 'click'
                    ,type: 'datetime'
                });
            });
            //多选框回显
            var formSelects = layui.formSelects;
            var questionnaireList = $("#checked").val();
            console.log(questionnaireList);
            let arr = JSON.parse(String(questionnaireList))
            formSelects.value('select9', arr, true);
            formSelects.btns('select9', ['remove']);
        });
    
        $(function(){
            $("#form-materialMart-add").validate({
                rules:{
                    type:{
                        required: true,
                    },
                    userId:{
                        required: true,
                    },
                    projectSortId:{
                        required: true,
                    },
                    title:{
                        required: true,
                    },
                    Icon:{
                        required: true,
                    },
                    content:{
                        required: true,
                    },
                    introduction:{
                        required: true,
                    },
                    price:{
                        required: true,
                    },
                    phoneNumber:{
                        required: true,
                    },
                    createTime:{
                        required: true,
                    },
                    updateTime:{
                        required: true,
                    },
                    isGoods:{
                        required: true,
                    },
                },
                onkeyup:false,
                debug: true,
                success:"valid",
                submitHandler:function(form){
                    $(form).ajaxSubmit({
                        type: 'POST',
                        url: "/admin/materialMart/edit" ,
                        success: function(data){
                            if(data.code == "1"){
                                selfmsg('修改成功!',1,function(){
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.location.reload();
                                    parent.layer.close(index);
                                });
                            }else{
                                selfmsg('修改失败!');
                            }
                        },
                        error: function(){
                            selfmsg('修改异常!',5);
                        }
                    });
                }
            });
        });
    
    </script>
    <!--上传图片-->
    <script>
        //删除图片
        function closeImg(obj) {
            $(obj).parent().remove();
            // var goods_img = '';
            // $('.imgcon .img_div').each(function () {
            //     goods_img += $(this).find('img').attr('src') + ',';
            // })
            $('.meetingIcon').val('');
            if ($('.imgcon').children().length == 1) {
                $('.addimg').css('display', 'none');
            }
            if ($('.imgcon').children().length < 1) {
                $('.addimg').css('display', 'inline-block');
            }
        }
        //上传图片
        $(function () {
            $('#fileupload').fileupload({
                dataType: 'json',
                dropZone: $('#drag'),
                change: function (e, data) {
                    var len = $('.imgcon').children().length;
                    if (data.files.length > (1 - parseInt(len))) {
                        layer.msg('最多上传1张图片');
                        return false;
                    }
                },
                start: function (e) {
                    layer_msg = layer.msg('正在上传中…', {time: 100000000});
                },
                progressall: function (e, data) {
                    $('.layui-layer-msg .layui-layer-content').html('已上传' + (data.loaded / data.total * 100).toFixed(2) + '%');
                },
                done: function (e, data) {
                    layer.close(layer_msg);
                    callback(data.result.msg);
                }
            });
            $('#drag').bind('drop dragover', function (e) {
                e.preventDefault();
            }).on('dragenter', function (e) {
                $(this).addClass('dragenter');
            }).on('drop', function (e) {
                $(this).removeClass('dragenter');
            }).on('dragleave', function (e) {
                $(this).removeClass('dragenter');
            });
    
            /**
             * 数据回调
             * @param id
             * @param value
             */
            function callback(value) {
                var $li = $(
                    "<div class=\"img_div\">" +
                    "<a οnclick=\"$(this).attr('href', $(this).find('img').attr('src'))\" type=\"button\"  data-lightbox=\"preview\">" +
                    "<img src=\"" + value + "\" alt=\"\" style='height: 100px;width: 100px'>" +
                    "</a>" +
                    "<i class='layui-icon layui-icon-delete close' οnclick='closeImg(this)'></i>" +
                    "</div>"
                );
                $('.imgcon').append($li);
                if ($('.imgcon').children().length == 1) {
                    $('.addimg').css('display', 'none');
                }
                // var goods_img = '';
                // $('.imgcon .img_div').each(function () {
                //     goods_img += $(this).find('img').attr('src') + ',';
                // })
                $('.goods_img').val($(this).find('img').attr('src'));
            }
    
            //图片回显
            if ("$document.getElementsByName('name')" != '') {
                var goods_img = $(document.getElementsByName('name'));
                $('.goods_img').val(goods_img);
                // var arr = goods_img.split(',');
                // for (var i = 0; i < arr.length; i++) {
                //     if (arr[i] != '') {
                //         callback(arr[i]);
                //     }
                // }
                if ($('.imgcon').children().length == 1) {
                    $('.addimg').css('display', 'none');
                }
    
            }
        });
    </script>
    <!--/请在上方写此页面业务相关的脚本-->
    </body>
    </html>
    

    后端代码:

    package com.mbyte.easy.admin.controller;
    
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.core.metadata.IPage;
    import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.mbyte.easy.admin.entity.MaterialMart;
    import com.mbyte.easy.admin.entity.MaterialProject;
    import com.mbyte.easy.admin.entity.ProjectSort;
    import com.mbyte.easy.admin.entity.RecommendMenuSecond;
    import com.mbyte.easy.admin.service.IMaterialMartService;
    import com.mbyte.easy.admin.service.IMaterialProjectService;
    import com.mbyte.easy.admin.service.IProjectSortService;
    import com.mbyte.easy.common.controller.BaseController;
    import com.mbyte.easy.common.web.AjaxResult;
    import com.mbyte.easy.util.OssFileUtils;
    import com.mbyte.easy.util.OssUtil;
    import com.mbyte.easy.util.PageInfo;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.time.LocalDateTime;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
    * <p>
    * 物料商城内容管理
    * </p>
    * @author 吕金彪
    * @since 2019-09-21
    */
    @Slf4j
    @Controller
    @RequestMapping("/admin/materialMart")
    public class MaterialMartController extends BaseController  {
    
        private String prefix = "admin/materialmart/";
    
        @Autowired
        private IMaterialMartService materialMartService;
        @Autowired
        private IMaterialProjectService materialProjectService;
    
        /**
        * 查询列表
        *
        * @param model
        * @param pageNo
        * @param pageSize
        * @param materialMart
        * @return
        */
        @RequestMapping
        public String index(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, MaterialMart materialMart) {
            Page<MaterialMart> page = new Page<MaterialMart>(pageNo, pageSize);
            IPage<MaterialMart> pageInfo = materialMartService.listPage(materialMart,page);
            model.addAttribute("searchInfo", materialMart);
            model.addAttribute("pageInfo", new PageInfo(pageInfo));
            return prefix+"list";
        }
    
        /**
        * 添加跳转页面
        * @return
        */
        @GetMapping("addBefore")
        public String addBefore(Model model){
            List<RecommendMenuSecond> recommendMenuSeconds = materialMartService.selectAllType();
            model.addAttribute("recommendMenuSeconds",recommendMenuSeconds);
            return prefix+"add";
        }
    
        /**
         * 添加页面图片保存跳转
         */
        String path = "";
    
        @PostMapping("addFile")
        @ResponseBody
        public AjaxResult addFile(@RequestParam("imageFile") MultipartFile imageFile) {
            path = OssFileUtils.uploadSingleFile(imageFile);
            return success(path);
        }
    
        /**
        * 添加
        * @param materialMart
        * @return
        */
        @RequestMapping("add")
        @ResponseBody
        public AjaxResult add(MaterialMart materialMart, String typeId){
            materialMart.setShareNumber(0);
            materialMart.setCreateTime(LocalDateTime.now());
            materialMart.setUpdateTime(LocalDateTime.now());
            if(materialMart.getPrice()==null){
                materialMart.setPrice(0);
            }
            //上传图片
            materialMart.setIcon(path);
            log.info("path:"+path);
            //分割字符串typeId
            String[] strArr= StringUtils.split(typeId,",");
    
            //插入新建项目
            int change = materialMartService.insertAllMart(materialMart);
            log.info("change"+change);
            //插入对应类型到中间表
            MaterialProject materialProject=new MaterialProject();
            for (int i = 0; i < strArr.length; i++) {
                materialProject.setMaterialMartId( materialMart.getId());
                materialProject.setProjectSortId(Long.valueOf(strArr[i]));
                materialProject.setCreateTime(LocalDateTime.now());
                materialProject.setUpdateTime(LocalDateTime.now());
                materialMartService.insertMartType(materialProject);
            }
    
            return toAjax(change);
        }
        /**
        * 添加跳转页面
        * @return
        */
        @GetMapping("editBefore/{id}")
        public String editBefore(Model model,@PathVariable("id")Long id){
            //回显所有数据
            model.addAttribute("materialMart",materialMartService.getById(id));
            QueryWrapper<MaterialProject> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("material_mart_id",id);
            List<MaterialProject> materialProjects = materialProjectService.selectList(queryWrapper);
            List<Long> list=new ArrayList<>();
            for (MaterialProject materiaProject:materialProjects) {
                list.add(materiaProject.getProjectSortId());
            }
    
            //回传所有类型
            List<RecommendMenuSecond> recommendMenuSeconds = materialMartService.selectAllType();
            model.addAttribute("materialProjects",list);
            model.addAttribute("recommendMenuSeconds",recommendMenuSeconds);
            return prefix+"edit";
        }
        /**
        * 添加
        * @param materialMart
        * @return
        */
        @PostMapping("edit")
        @ResponseBody
        public AjaxResult edit(MaterialMart materialMart,
                               @RequestParam(required = false) String title,
                               @RequestParam(required = false) String content,
                               @RequestParam(required = false) Integer price,
                               @RequestParam(required = false) Integer phoneNumber,
                               String typeId){
            materialMart.setTitle(title);
            materialMart.setContent(content);
            materialMart.setPrice(price);
            materialMart.setPhoneNumber(phoneNumber);
            materialMart.setUpdateTime(LocalDateTime.now());
            //上传图片
            materialMart.setIcon(path);
    
            if(typeId!=null&&typeId!="") {
                //分割字符串typeId
                String[] strArr = StringUtils.split(typeId, ",");
                //删除该项目原属类
                materialMartService.deleteByMartId(materialMart.getId());
                //插入类型到中间表
                MaterialProject materialProject = new MaterialProject();
                for (int i = 0; i < strArr.length; i++) {
                    materialProject.setMaterialMartId(materialMart.getId());
                    materialProject.setProjectSortId(Long.valueOf(strArr[i]));
                    materialProject.setCreateTime(LocalDateTime.now());
                    materialProject.setUpdateTime(LocalDateTime.now());
                    materialMartService.insertMartType(materialProject);
                }
            }
            return toAjax(materialMartService.updateById(materialMart));
        }
        /**
        * 删除
        * @param id
        * @return
        */
        @GetMapping("delete/{id}")
        @ResponseBody
        public AjaxResult delete(@PathVariable("id") Long id){
            //删除该项目原属类
            materialMartService.deleteByMartId(id);
            return toAjax(materialMartService.removeById(id));
        }
        /**
        * 批量删除
        * @param ids
        * @return
        */
        @PostMapping("deleteAll")
        @ResponseBody
        public AjaxResult deleteAll(@RequestBody List<Long> ids){
            //删除项目原属类
            for (Long id:ids) {
                materialMartService.deleteByMartId(id);
            }
            return toAjax(materialMartService.removeByIds(ids));
        }
    
    }
    
    
    
    展开全文
  • 起初我给layui表格的数据接口绑定的是一个json文件,但是这是静态的,如果在运行中创建json文件,表格会找不到相应的json文件。 于是在controller中创建相应该url的方法,返回json数据的方法,从而动态的显示表格...

    起初我给layui表格的数据接口绑定的是一个json文件,但是这是静态的,如果在运行中创建json文件,表格会找不到相应的json文件。
    于是在controller中创建相应该url的方法,返回json数据的方法,从而动态的显示表格信息。

    layui数据接口的格式要求:

    {
      "code": 0,
      "msg": "",
      "count": 1000,
      "data": [{}, {}]
    } 
    

    HTML中的片段代码:

    <script type="text/javascript" src="/layui/layui.js"></script>
          <script>
            layui.use('table', function(){
              var table = layui.table;
    
              //第一个实例
              table.render({
                elem: '#demo'
                ,height: 600
                ,url: '/paper_info' //数据接口
                ,page: true //开启分页
                ,title: '教师信息'
                ,cols: [[ //表头
                  {field: '_id', title: 'ID', width:220, sort: true,event: 'clos'}
                  ,{field: 'index', title: '所属教师', width:100, event: 'clos'}
                  ,{field: 'title', title: '标题', width:250, event: 'clos'}
                  ,{field: 'authors', title: '作者列表', width:200, event:'clos'}
                  ,{field: 'source', title: '论文来源', width: 200, event: 'clos'}
                  ,{field: 'times', title: '时间', width: 130, sort: true, event:'cols'}
                  ,{field: 'database', title: '论文种类', width: 120, sort: true, event: 'clos'}
                  ,{field: 'counted', title: '引用次数', width: 100, sort: true, event: 'clos'}
                  ,{field: 'toolbar', title: '工具栏', width: 170, toolbar: '#barDemo'}
                ]]
              });
              });
            });
          </script>
    

    在Controller中配置该url:

    @ResponseBody
        @RequestMapping("/paper_info")
        public String paperInfo() throws IOException{
            Convert2json convert2json  = new Convert2json(mongoTemplate); //该方法是我项目中可以返回json的Method
            return convert2json.saveAsJson();
        }
    

    问题来了如果想要带参数的url该怎么办?
    HTML代码

     <script src="/layui/layui.js"></script>
        <script>
            layui.use('table', function(){
                var table = layui.table;
                var author = window.location.href.split("=")[1]
                //第一个实例
                table.render({
                    elem: '#demo'
                    ,height: 600
                    ,url: '/paperList?author='+author //数据接口
                    ,page: true //开启分页
                    ,title: '教师信息'
                    ,cols: [[ //表头
                        {field: '_id', title: 'ID', width:220, sort: true,event: 'clos'}
                        ,{field: 'index', title: '所属教师', width:100, event: 'clos'}
                        ,{field: 'title', title: '标题', width:250, event: 'clos'}
                        ,{field: 'authors', title: '作者列表', width:200, event:'clos'}
                        ,{field: 'source', title: '论文来源', width: 200, event: 'clos'}
                        ,{field: 'times', title: '时间', width: 130, sort: true, event:'cols'}
                        ,{field: 'database', title: '论文种类', width: 120, sort: true, event: 'clos'}
                        ,{field: 'counted', title: '引用次数', width: 100, sort: true, event: 'clos'}
                        ,{field: 'toolbar', title: '工具栏', width: 170, toolbar: '#barDemo'}
                    ]]
                });
        </script>
    

    ** 我们在url中添加了参数author ,可以在controller中对该参数进行解析:**

        @ResponseBody //可以利用@RequestParam标记来解析url中的参数
        @RequestMapping("/paperList")
        public String paperList(@RequestParam("author") String name) throws IOException { 
            AuthorPaper2json authorPaper2json = new AuthorPaper2json(mongoTemplate);
            return authorPaper2json.saveAsJson(name);
        }
    

    如果不太会构建相应的json数据,尤其是mongoDB的数据可以看我以往写过的文章:
    https://blog.csdn.net/qq_36801317/article/details/107408397
    希望大家批评指正~

    展开全文
  • ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>' ,'</td>' ,'</tr>'].join('')); //单个重传 tr.find('.demo-reload').on('click', ...

    1.tag代码

    <script type="text/javascript" data-th-inline="javascript">
    	var xhrOnProgress=function(fun) {
    		xhrOnProgress.onprogress = fun; //绑定监听
    		//使用闭包实现监听绑
    		return function() {
    			//通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
    			var xhr = $.ajaxSettings.xhr();
    			//判断监听函数是否为函数
    			if (typeof xhrOnProgress.onprogress !== 'function')
    				return xhr;
    			//如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
    			if (xhrOnProgress.onprogress && xhr.upload) {
    				xhr.upload.onprogress = xhrOnProgress.onprogress;
    			}
    			return xhr;
    		}
    	}
    
    	$(document).ready(function() {
    		layui.use(['upload','element','layer'], function(){
    			var $ = layui.jquery;
    			var upload = layui.upload,element = layui.element,layer = layui.layer;
    			//多文件列表示例
    			var count=0;
    			var context=$("[name=context]").val();
    			var demoListView = $('#${id}fList')
    					,uploadListIns = upload.render({
    				elem: '#${id}upList'
    				,url: '${url}'
    				,accept: 'file'
    				,size:'${filesize}'
    				,multiple:${isMultiple}
    				,xhr:xhrOnProgress
    				,progress:function(value,obj){//上传进度回调 value进度值
    					$("#${id}fList").find('.layui-progress ').each(function () {
    						if(	$(this).attr("file")==obj.name){
    							var progressBarName=	$(this).attr("lay-filter");
    							var percent=Math.floor((value.loaded / value.total)*100);//计算百分比
    							element.progress(progressBarName, percent+'%')//设置页面进度条
    						}
    					})
    
    				}
    				,auto: false
    				,bindAction: '#${id}upListAction'
    				,choose: function(obj){
    					var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
    					//读取本地文件
    					obj.preview(function(index, file, result){
    						count++;
    						var tr = $(['<tr id="${id}upload-'+ index +'">'
    							,'<td>'+ file.name +'</td>'
    							,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
    							,'<td>'
    							+'<div  file="'+file.name+'" class="layui-progress layui-progress-big" lay-showpercent="true"   lay-filter="progressBar'+count+'">'
    							+'<div  class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>'
    							+'</div>'
    							, '</td>'
    							,'<td>等待上传</td>'
    							,'<td>'
    							,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
    							,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
    							,'</td>'
    							,'</tr>'].join(''));
    
    						//单个重传
    						tr.find('.demo-reload').on('click', function(){
    							obj.upload(index, file);
    						});
    
    						//删除
    						tr.find('.demo-delete').on('click', function(){
    							delete files[index]; //删除对应的文件
    							tr.remove();
    							uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
    						});
    
    						demoListView.append(tr);
    					});
    				}
    				,done: function(res, index, upload){
    					if(res.code == 1){ //上传成功
    
    						if($("#${id}fList").val() == ""){
    							$("#${id}fList").val(res.url);
    						}else{
    							$("#${id}fList").val($("#${id}fList").val()+"@@files@@"+res.url);
    						}
    						var tr = demoListView.find('tr#${id}upload-'+ index)
    								,tds = tr.children();
    						tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
    						tds.eq(4).html(''); //清空操作
    						return delete this.files[index]; //删除文件队列已经上传成功的文件
    					}
    					this.error(res,index, upload);
    				}
    				,error: function(res,index, upload){
    					//element.progress('progressBar', '0%');
    					var tr = demoListView.find('tr#${id}upload-'+ index)
    							,tds = tr.children();
    					tds.eq(3).html('<span style="color: #FF5722;">上传失败,'+res.msg+'</span>');
    					tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
    				}
    			});
    		})
    	});
    </script>
    
    <div class="layui-input-block layui-btn-container">
    	<button type="button" class="btn btn-white btn-sm" id="${id}upList">${labelname}</button>
    	<button type="button" class="btn btn-white btn-sm" id="${id}upListAction">开始上传</button>
    </div>
    <div class="layui-input-block">
    	<div class="layui-upload">
    		<div class="layui-upload-list">
    			<table class="layui-table">
    				<thead>
    				<tr><th>文件名</th>
    					<th>大小</th>
    					<th>上传进度</th>
    					<th>状态</th>
    					<th>操作</th>
    				</tr></thead>
    				<tbody id="${id}fList" value="${value}"></tbody>
    			</table>
    		</div>
    
    	</div>
    </div>

    目录:

    2.前端tag调用示例:

    <!DOCTYPE html>
    <html xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <#inc:head/>
        <script type="text/javascript">
            $(document).ready(function() {
                $("#btnImport").click(function(){
                    //验证选择文件后必须上传完成才能提交
                    var flag = false;
                    $("#testfList").find('.layui-progress ').each(function () {
                        if($(this).children().attr("style") != "width: 100%;") {
                            flag = true;
                            return;
                        }
                    })
                    if(flag){
                        top.layer.alert('请先上传选择的文件!', {icon: 0, title: '提示'});
                        return;
                    }
                    alert("文件路径:"+$("#testfList").val())
                });
            });
    
        </script>
    </head>
    <body class="layui-layout-body" style="overflow: auto;">
    <div class="layui-form-item">
        <label class="layui-form-label">输入框</label>
        <div class="layui-input-block">
            <input type="text" id="fileTitle" name="fileTitle" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">文本域</label>
        <div class="layui-input-block">
            <textarea id="remarks" name="remarks" placeholder="请输入" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
       <#fileImport:multifile
            id="test"
            filesize="2048"
            isMultiple="true"
            labelname="上传文件"
            value=""
            url="${ctx}/filetest/uploadmulti3/"
        />
    </div>
    
    <div class="layui-input-block layui-btn-container">
        <button type="button" class="btn btn-white btn-sm" id="btnImport">模拟提交</button>
    </div>
    </body>
    </body>
    
    </html>

     

    3、后端controller实现

    @Controller
    @RequestMapping(value = "${adminPath}/filetest")
    public class FilesTestController extends BaseController {
    
        @PostMapping("uploadmulti3")
        @ResponseBody
        public Map<String, Object> noticeFile(HttpServletRequest request, @RequestParam(name = "file") MultipartFile files) {
            Map<String, Object> resMap  = FileUtils.uploadFile2(files,"");
            return resMap;
        }
    
        @RequestMapping("home9")
        public ModelAndView home9(){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("modules/file/uploadMulti3.html");
            return modelAndView;
        }
    }

    4、上传代码实现

    public static Map<String, Object> uploadFile2(MultipartFile fileList,String filePath) {
       try {
          filePath ="D:\\files\\"+filePath;
          //String timeMillis = Long.toString(System.currentTimeMillis());// 时间戳
          String filename =  fileList.getOriginalFilename();
          File dir = new File(filePath);
          if (!dir.exists()) {
             dir.mkdirs();
          }
          String endpath = filePath + filename;
          File serverFile = new File(endpath);
          fileList.transferTo(serverFile);
          Map<String, Object> map = new HashMap<String, Object>();
          map.put("code", "1");
          map.put("url", endpath);
          return map;
    
       } catch (Exception e) {
          e.printStackTrace();
          Map<String, Object> map = new HashMap<String, Object>();
          map.put("code", "0");
          return map;
       }
    }

    5、layui upload.js修改,放置工程目录覆盖原有的

               layui.each(a, function (e, a) {
                    var r = new FormData;
                    r.append(l.field, a), layui.each(l.data, function (e, i) {
                        i = "function" == typeof i ? i() : i, r.append(e, i)
                    }), i.ajax({
                        url: l.url,
                        type: "post",
                        data: r,
                        contentType: !1,
                        processData: !1,
                        dataType: "json",
                        xhr:l.xhr(function(e){//此处为新添加功能
                            var percent=Math.floor((e.loaded / e.total)*100);//计算百分比
                            l.progress(e,a);//回调将数值返回
                            //console.log(e,"e2")
                        }),
                        headers: l.headers || {},
                        success: function (i) {
                            t++, d(e, i), u()
                        },
                        error: function () {
                            n++, o.msg("请求上传接口出现异常"), m(e), u()
                        }
                    })
                })

    6、实现效果

    备注:多文件路径的拼接可以通过 组件value获得,用于和其他数据一起表单提交

    展开全文
  • Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。这篇文章主要介绍了SpringBoot+layui实现文件上传,需要的朋友可以参考下
  • 本项目由springboot+mybatis+layui 为框架开发的javaweb 后台管理系统,
  • 内附数据库源码,项目源码,运行截图,启动步骤说明。 根据操作步骤一步一步运行
  • 使用SpringBoot+layui +Echarts开发数据统计图表(柱形图,饼图,折现图)案例中统计的数据是港口生产作业收入分析统计走势。
  • springboot+layui实现文件上传,这个案例只有上传,没有其他多余的操作
  • 项目有演示视频(任选博主一篇文章,最下方),便于各位老板遴选,先看再选,满意付款,您满意的才是最好的
  • 后台管理系统 ├─.idea ├─src --------主目录 │ ├─main │ │ ├─java ...│ │ │ │ └─blog │ │ │ │ └─manager │ │ │ │ ├─common ---- 存放工具类 │ │ │ │ │ └─utils ...
  • springboot整合项目layui

    2018-07-24 13:49:49
    里面包含了 前后台的调用 和layui的引用类 上传图片等功能 http://localhost:20180/merchantCheck/hotComments/ 链接地址 http://localhost:20180/merchantCheck/rmpl/userList.html 一个经过后台来显示页面 一个...
  • 基于SpringBootLayUI的后台管理系统 一套SpringBoot+MyBatis+FreeMarker+LayUI的后台管理系统. 适用于小体量,CRUD业务为主的后台系统快速搭建和学习. 在学习过程中发现很多地方网上没有给出一个整套的案例, 因此...
  • springboot-layui.rar

    2020-08-25 00:42:48
    springboot+layui文件上传demo,本人工作因为项目中使用,自行创建demo。后续将上传excel读取方法easyExcel
  • 基于springbootlayui,activiti的青锋后台管理系统 介绍 青锋后台管理系统是一种基于springbootlayui,activiti工作流,实现了代码生成器,自定义表格,拖曳可视化报表大屏的后台脚手架系统,包含基础架构的常用...
  • layui三级动态菜单(SpringBoot项目)简单demo仅供参考。
  • SpringBoot引入layui

    千次阅读 2021-04-23 22:26:59
    SpringBoot引入layui 进入layui官方下载: https://www.layui.com/ 下载完是个压缩包进行解压缩 在resource下创建static文件夹,把解压缩好的复制进去 jsp添加引用 <!--引入layui的css--> <link rel=...
  • springboot+layui基础项目

    千次阅读 多人点赞 2020-12-16 15:02:40
    springboot+layui Demo 在线地址:http://123.57.129.17:9001 源码地址:https://gitee.com/zhoukaishun/kaishun_zhou 测试账号密码:admin 123456 适用人群 新手入门,职场新人 已有功能 目前包含基本的登录...
  • SpringBoot整合LayUI

    千次阅读 2020-09-17 10:37:52
    Springboot框架整合使用Layui,配置过程如下: 一、新建Springboot工程 配置POM: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>...
  • 一个简易的商城项目,可开箱即用
  • <link rel="stylesheet" href="/layui/css/layui.css"> <table id="changshang" lay-filter="changshang" style="width: 100%"></table> <script src="/layui/layui.all
  • java 代码 @RequestMapping("/stuInfoAllRest") public String stuInfoAllRest(String page,String limit,HttpSession session, HttpServletRequest request, Map<String, Object> map) { ...
  • 1.实现拖拽上传,前台渲染并上传到数据库 先去看layui官网代码,分析了解后台需要返回什么数据 2.完整数据表格的时候 使用过程太复杂 详细代码请下载 springboot+layui数据表格
  • 本期给大家推荐我自己写一个开源项目:springboot-mini,本着减少大量重复开发工作的原则,使得在项目中...前端框架使用 layui-mini(https://gitee.com/zhongshaofa/layuimini) 2、项目地址 https://gitee.com/asu

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,769
精华内容 2,307
关键字:

springbootlayui

spring 订阅