springboot+layui实现增删查改

本文描述springboot和layui的结合,采用了springboot内置的jdbc,根据不同需要可以进行修改;分页采用了layui中自带分页格式!
-------------------------------------------------数据管理dao层
package main.springboot.dao;

import main.springboot.bean.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

    /**
     * 教师DAO
     * @author 周帅
     */
    @Repository
    public class TeaDao extends PageDao{

        @Autowired
        private JdbcTemplate jdbcTemplate;


        /**
         * 查询所有学生
         * @return
         */
        public List queryTea(String newname){
            String sql = "select * from t_tea where flag=1";
            System.out.println(newname+"   aaaaa");
            if(newname!=null){
                sql +=" and name like '%"+newname+"%'";
            }
            System.out.println(sql);
            return jdbcTemplate.queryForList(sql);
        }

        /**
         * 获取用户信息
         * @param id
         * @return
         */
        public Map getTea(int id){
            String sql = "select * from t_tea where id="+id;
            return jdbcTemplate.queryForMap(sql);
        }

        /**
         * 更新教师信息
         * @param TeaMap
         */
        public void updateTea(Map TeaMap){
            String name = TeaMap.get("name").toString();
            String sex = (String) TeaMap.get("sex");
            String age = (String) TeaMap.get("age");
            System.out.println(sex);
            System.out.println(age);
            String updatesql = "";
            if(name!=null){
                updatesql +="name='"+name+"',";
            }
            if(sex!=null){
                updatesql +="sex="+sex+",";
            }
            if(age!=null){
                updatesql +="age="+age;
            }
            System.out.println(TeaMap.get("id")+"aaaaaaawww");
            if(updatesql.length()>2){
                String sql = "update t_tea set "+updatesql+" where id="+TeaMap.get("id");
                jdbcTemplate.execute(sql);
            }
        }

        /**
         * 添加教师
         * @param TeaMap
         */
        public void addTea(Map TeaMap){
            String sql="insert into t_tea(name,sex,age,flag) values('"+TeaMap.get("name")+"',"+TeaMap.get("sex")+","+TeaMap.get("age")+",'1')";
            jdbcTemplate.execute(sql);
        }

        /**
         * 删除教师
         * @param id
         */
        public void deleteTea(String  id){
            String sql="update t_tea set flag='0' where id in("+id+")";
            jdbcTemplate.execute(sql);
        }

        /**
         * 模糊查询
         * @param pageBean
         * @param where
         * @param orderby
         * @return
         */
        public PageBean mohuquery(PageBean pageBean, String where, String orderby){
            String sql="select * from t_tea where flag=1 " ;
            return this.queryPageByMysql(pageBean, sql, where, orderby);
        }
}

-----------------------------------------------------------pageDao分页查询

package main.springboot.dao;

import java.util.List;
import java.util.Map;

import main.springboot.bean.PageBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class PageDao {
   
   @Autowired
   private JdbcTemplate jdbcTemplate;
   
   /**
    * 分页查询
    * @param sql
    * @param where
    * @param orderby
    * @return
    */
   public PageBean queryPageByMysql(PageBean pageBean,String sql,String where,String orderby){
      int page = pageBean.getPage();
      int rows = pageBean.getRows();
      int startIndex = (page-1) * rows;
      String pageSql = sql+where+orderby+" limit "+startIndex+","+rows;
      System.out.println(pageSql);
      System.out.println("PageBean Sql语句:"+pageSql);

      List list = jdbcTemplate.queryForList(pageSql);
      System.out.println("PageBean 查询数据:"+list);
      pageBean.setPageData(list);
      int total = this.queryTotal(sql, where);
      pageBean.setTotal(total);
      return pageBean;
   }
   
   /**
    * 分页查询
    * @param sql
    * @param where
    * @param orderby
    * @return
    */
   public PageBean queryPageByOracle(PageBean pageBean,String sql,String where,String orderby){
      int page = pageBean.getPage();
      int rows = pageBean.getRows();
      int startIndex = (page-1) * rows;
      int endIndex = page * rows;
      String pageSql = "SELECT * FROM (SELECT A.*, ROWNUM RN FROM ("+sql+where+orderby+") A WHERE ROWNUM <= "+endIndex+" ) WHERE RN > "+startIndex;
      List list = jdbcTemplate.queryForList(pageSql);
      pageBean.setPageData(list);
      int total = this.queryTotal(sql, where);
      pageBean.setTotal(total);
      return pageBean;
   }
   
   
   /**
    * 查询总数量
    * @param sql
    * @param where
    * @return
    */
   public int queryTotal(String sql,String where){
      String totalSql = " select count(1) as total from ("+sql+where+") a ";
      List list = jdbcTemplate.queryForList(totalSql);
      Map map = (Map)list.get(0);
      return Integer.parseInt(map.get("total").toString());
   }

}

-----------------------------------------------------------业务service层

package main.springboot.action;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import main.springboot.bean.PageBean;
import main.springboot.service.TeaService;
import main.springboot.service.UserService;
import main.springboot.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 教师控制层
 * @author 周帅
 */
@Controller
public class TeaAction {


    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TeaService teaService;
    @Autowired
    private UserService userService;

    private String newname ="";
    /**
     * 查询所有教师
     * @param request
     * @return
     */
    @RequestMapping("/view/system/queryTeaList")
    @ResponseBody
    public String queryRoleList(HttpServletRequest request){
        try {
            List list = teaService.queryTea(newname);
            JSONObject josn = new JSONObject();
            josn.put("code",0);
            josn.put("msg","");
            josn.put("data",JSONArray.toJSON(list));
            return josn.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据ID查询教师信息
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/view/system/queryById")
    @ResponseBody
    public Map queryById(HttpServletRequest request,@RequestParam int id){
        Map map = null;
        try {
            map = teaService.getTea(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 添加教师
     * @param request
     * @param teaMap
     * @return
     */
    @RequestMapping("/view/system/addTea")
    @ResponseBody
    public int addTea(HttpServletRequest request,@RequestParam Map teaMap){
        try {
            teaService.addTea(teaMap);
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 修改教师
     * @param request
     * @param teaMap
     * @return
     */
    @RequestMapping("/view/system/updateTea")
    @ResponseBody
    public int updateTea(HttpServletRequest request,@RequestParam Map teaMap){
        try {
            teaService.updateTea(teaMap);
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 删除教师
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/view/system/deleteTea")
    @ResponseBody
    public int deleteTea(HttpServletRequest request,@RequestParam String id){
        try {
            teaService.deleteTea(id);
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }


    /**
     * 图表数据查询
     * @return
     */
    @RequestMapping("/view/system/queryTea2")
    @ResponseBody
    public ResponseEntity queryTea2(){
        System.out.println(newname);
        List list = teaService.queryTea(newname);
        return  new ResponseEntity(list, HttpStatus.OK);
    }


    /**
     * 分页查询
     * @param request
     * @param queryParams
     * @return
     */
    @RequestMapping("/view/system/queryTea")
    @ResponseBody
    public Map queryTea(HttpServletRequest request,@RequestParam Map queryParams){
        Map result = new HashMap();
        try {
            PageBean pageBean = new PageBean();
            pageBean.setPage(Integer.parseInt(queryParams.get("page").toString()));
            pageBean.setRows(Integer.parseInt(queryParams.get("limit").toString()));
            newname = (String) queryParams.get("keyword");
            pageBean.setQueryParams(queryParams);
            pageBean = teaService.mohuquery(pageBean);
            result.put("count", pageBean.getTotal());
            result.put("data", pageBean.getPageData());
            result.put("msg", "");
            result.put("code", 0);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("count", 0);
            result.put("data", new ArrayList());
            result.put("msg", "");
            result.put("code", 500);
        }
        return result;
    }
}

----------------------------------------------------------------------控制action层

package main.springboot.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import main.springboot.bean.PageBean;
import main.springboot.service.TeaService;
import main.springboot.service.UserService;
import main.springboot.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 教师控制层
 * @author 周帅
 */
@Controller
public class TeaAction {


    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TeaService teaService;
    @Autowired
    private UserService userService;

    private String newname ="";
    /**
     * 查询所有教师
     * @param request
     * @return
     */
    @RequestMapping("/view/system/queryTeaList")
    @ResponseBody
    public String queryRoleList(HttpServletRequest request){
        try {
            List list = teaService.queryTea(newname);
            JSONObject josn = new JSONObject();
            josn.put("code",0);
            josn.put("msg","");
            josn.put("data",JSONArray.toJSON(list));
            return josn.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据ID查询教师信息
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/view/system/queryById")
    @ResponseBody
    public Map queryById(HttpServletRequest request,@RequestParam int id){
        Map map = null;
        try {
            map = teaService.getTea(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }


    /**
     * 添加教师
     * @param request
     * @param teaMap
     * @return
     */
    @RequestMapping("/view/system/addTea")
    @ResponseBody
    public int addTea(HttpServletRequest request,@RequestParam Map teaMap){
        try {
            teaService.addTea(teaMap);
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 修改教师
     * @param request
     * @param teaMap
     * @return
     */
    @RequestMapping("/view/system/updateTea")
    @ResponseBody
    public int updateTea(HttpServletRequest request,@RequestParam Map teaMap){
        try {
            teaService.updateTea(teaMap);
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 删除教师
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/view/system/deleteTea")
    @ResponseBody
    public int deleteTea(HttpServletRequest request,@RequestParam String id){
        try {
            teaService.deleteTea(id);
            return 0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }


    /**
     * 图表数据查询
     * @return
     */
    @RequestMapping("/view/system/queryTea2")
    @ResponseBody
    public ResponseEntity queryTea2(){
        System.out.println(newname);
        List list = teaService.queryTea(newname);
        return  new ResponseEntity(list, HttpStatus.OK);
    }


    /**
     * 分页查询
     * @param request
     * @param queryParams
     * @return
     */
    @RequestMapping("/view/system/queryTea")
    @ResponseBody
    public Map queryTea(HttpServletRequest request,@RequestParam Map queryParams){
        Map result = new HashMap();
        try {
            PageBean pageBean = new PageBean();
            pageBean.setPage(Integer.parseInt(queryParams.get("page").toString()));
            pageBean.setRows(Integer.parseInt(queryParams.get("limit").toString()));
            newname = (String) queryParams.get("keyword");
            pageBean.setQueryParams(queryParams);
            pageBean = teaService.mohuquery(pageBean);
            result.put("count", pageBean.getTotal());
            result.put("data", pageBean.getPageData());
            result.put("msg", "");
            result.put("code", 0);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("count", 0);
            result.put("data", new ArrayList());
            result.put("msg", "");
            result.put("code", 500);
        }
        return result;
    }

}

------------------------------------------------------------数据页面 




    
    
    
    
    
    
    
    
    
    
    




--------------------------------------------------------主要的tea.js

var table;
var layer;
layui.use([ 'layer', 'table', 'element' ], function() {
    table = layui.table;
    layer = layui.layer;
    // 执行一个 table 实例
    table.render({
        elem : '#user',
        height:472,
        url : '/view/system/queryTea',
        page :true, // 开启分页
        cols : [ [ // 表头
            {
                fixed : 'left',
                type : 'checkbox'
            }, {
                field : 'id',
                title : 'ID',
                width : 80,

                fixed : 'left'
            }, {
                field : 'name',
                title : '教师名称',
                width : 160
            }, {
                field : 'sex',
                title : '性别',
                width : 80,
                templet : function(d) {
                    if (d.sex == 1) {
                        return '男';
                    } else if (d.sex == 0) {
                        return '女';
                    }
                }
            }, {
                field : 'age',
                title : '年龄',
                width : 220,
            },{
                title : '操作',
                width : 300,
                align : 'center',
                toolbar : '#tools'
            } ] ]

    });

// 监听工具条
    table.on('tool(tools)', function(obj) { // 注:tool是工具条事件名,test是table原始容器的属性
        var data = obj.data // 获得当前行数据
            , layEvent = obj.event; // 获得 lay-event 对应的值
        if ('edit' == layEvent) {
            addTea(data.id)
        } else if ('del' == layEvent) {
            del(data.id);
        }
    });

    showBar();
});


function showBar() {
//生成图表
// 基于准备好的dom,初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));
    var m=0;
    var n=0;
    $.ajax({
        url:"/view/system/queryTea2",
        success:function(data){
            $.each(data,function (i,obj) {
                if(obj.sex==1){
                    m+=1;
                }else{
                    n+=1;
                }
            });
            // 指定图表的配置项和数据
            var option = {
                title: {
                    text: '男女比例'
                },
                tooltip: {},
                legend: {
                    data:['数量']
                },
                xAxis: {
                    data: ["男","女"]
                },
                yAxis: {},
                series: [{
                    name: '数量',
                    type: 'bar',
                    data: [m,n]
                }]
            };
// 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        }
    });
}





function queryTea(){
    var keyword = $("#keyword").val();
    table.reload('user', {
        where : {
            keyword : keyword
        },
        page : {
            curr : 1
        }
    });
    showBar()
    }


var index;
function addTea(id) {
    index = layer.open({
        type : 2,
        title : "角色信息",
        content : '/view/system/editTea?id=' + id
    });
    layer.full(index);
    queryTea();
}

function close() {
    layer.close(index);
}

function del(id) {
        layer.open({
            type : 1,
            content : '
确定删除记录?
', btn : [ '确定', '取消' ], yes : function(index, layero) { $.ajax({ url : "/view/system/deleteTea", data : { "id" : id }, dataType : "text", success : function(data) { if(data==0){ layer.msg("删除成功!"); layer.close(index); queryTea(); }else{ layer.msg("删除失败!"); } }, error : function() { } }); } }); } /** * 获取选中数据 */ function getDatas(){ var checkStatus = table.checkStatus('user'); var data = checkStatus.data; var id = ""; for(var i=0;i

-----------------------------------------------------------------添加、修改页面




    
    
    
    
    
    
    
    
    
    


 

你可能感兴趣的:(java开发,springboot,layui,增删查改)