• layui的CRUD案例


    用layui来实现一个简单的二级权限和增删改查案列

       利用layui提供的组件(table , layer , form,tree来进行开发

    写一个简单的登录界面   根据用户的ID来 获取用户所对应的权限

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
     <form action="${pageContext.request.contextPath }/userAction.action?methodName=login" method="post"> 
        <input type="text" name="uid" ><br>
        <input type="text" name="upwd" ><br>
        <input type="submit" ><br>
     </form> 
    </body>
    </html>

    Userdao

    package com.liuwenwu.dao;
    import java.sql.SQLException;
    import java.util.List;
    import java.util.Map;
    import com.liuwenwu.util.JsonBaseDao;
    import com.liuwenwu.util.JsonUtils;
    import com.liuwenwu.util.PageBean;
    import com.liuwenwu.util.StringUtils;
    
    public class UserDao extends JsonBaseDao {
    
        /**
         * 登录 查询用户表
         * @return
         * @throws SQLException 
         * @throws IllegalAccessException 
         * @throws InstantiationException 
         */
        public List<Map<String, Object>> list(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
            String sql="select * from t_easyui_user_version2 where true";
            String uid=JsonUtils.getParamVal(paMap, "uid");
            String upwd=JsonUtils.getParamVal(paMap, "upwd");
            if(StringUtils.isNotBlank(uid)) {
                sql=sql+" and uid="+uid;
            }
            if(StringUtils.isNotBlank(upwd)) {
                sql=sql+" and upwd="+upwd;
            }
            return super.executeQuery(sql, pageBean);
        }
        
        /**
         * 通过中间表查询登录用户所对应的权限
         * @param paMap
         * @param pageBean
         * @return
         * @throws InstantiationException
         * @throws IllegalAccessException
         * @throws SQLException
         */
        public List<Map<String, Object>> listMenu(String uid,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
            String sql="select * from t_easyui_usermenu where true";
            if(StringUtils.isNotBlank(uid)) {
                sql=sql+" and uid="+uid;
            }
            return super.executeQuery(sql, pageBean);
        }
    }

    Mebudao 查询用户权限 并将数据转换成layui所识别的格式

    package com.liuwenwu.dao;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import com.liuwenwu.entity.TreeNode;
    import com.liuwenwu.util.JsonBaseDao;
    import com.liuwenwu.util.JsonUtils;
    import com.liuwenwu.util.PageBean;
    import com.liuwenwu.util.StringUtils;
    
    public class MenuDao extends JsonBaseDao {
    
        /**
         * @param map   req.getParameterMap
         * @param pageBean  分页
         * @return
         * @throws Exception 
         */
        public List<TreeNode> list(Map<String, String[]> map,PageBean pageBean) throws Exception{
            List<Map<String, Object>> listMenu=this.listMenuSef(map, pageBean);
            List<TreeNode> treeNodeList=new ArrayList<>();
            menuList2TreeNodeList(listMenu, treeNodeList);
            return treeNodeList;
        }
        
        public List<Map<String, Object>> listMenuSef(Map<String, String[]> map,PageBean pageBean)throws Exception{
            String sql=" select * from t_easyui_menu where true";
            String id=JsonUtils.getParamVal(map, "menuHid");
            if(StringUtils.isNotBlank(id)) {
                sql=sql +" and menuid in("+id+")";    
            }
            else {
                sql=sql+" and menuid =-1";
            }
            
            return super.executeQuery(sql, pageBean);
        }
        
        /**
         * 查询Menu表的数据
         * @param map
         * @param pageBean
         * @return
         */
        public List<Map<String, Object>> listMenu(Map<String, String[]> map,PageBean pageBean)throws Exception{
            String sql=" select * from t_easyui_menu where true";
            String id=JsonUtils.getParamVal(map, "id");
            if(StringUtils.isNotBlank(id)) {
                sql=sql +" and parentid ="+id;    
            }
            else {
                sql=sql+" and parentid =-1";
            }
            
            return super.executeQuery(sql, pageBean);    
        }
        
        /**
         * menu表的数据不符合layui树形展示的数据格式
         * 需要转换成layui所能识别的数据格式
         * @param map
         * @param reTreeNode
         * @throws Exception 
         */
        private void menu2TreeNode(Map<String, Object> map, TreeNode treeNode) throws Exception {
            treeNode.setId(map.get("Menuid").toString());
            treeNode.setName(map.get("Menuname").toString());
            treeNode.setAttributes(map);
            //转换格式
            Map<String, String[]> jspMap=new HashMap<>();
            jspMap.put("id", new String[] {treeNode.getId()});
            List<Map<String, Object>> listMenu=this.listMenu(jspMap, null);
            List<TreeNode> treeNodeList=new ArrayList<>();
            menuList2TreeNodeList(listMenu, treeNodeList);
            treeNode.setChildren(treeNodeList);    
        }    
    
        /**
         * @param mapList
         * @param treeNodeList
         * @throws Exception
         */
        private void menuList2TreeNodeList(List<Map<String, Object>> mapList, List<TreeNode> treeNodeList)throws Exception {
            TreeNode treeNode =null;
            for (Map<String, Object> map : mapList) {
                treeNode =new TreeNode();
                menu2TreeNode(map, treeNode);
                treeNodeList.add(treeNode);        
            }    
        }
        
    }

    index.jsp 树形菜单展示界面  注意layui css 和 js 文件的引用

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css">   
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/layui/css/index.css">  
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/layui.all.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/jquery-3.3.1.js"></script> 
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/index.js"></script>  
    <title>Insert title here</title>
    </head>
    
    <body >
    <div class="layui-layout layui-layout-admin " id="app">
        <div class="layui-header">
            <div class="layui-logo">后台管理界面</div>
            <!-- 头部区域(可配合layui已有的水平导航) -->
            <ul class="layui-nav layui-layout-right">
                <li class="layui-nav-item"><a href="#" onclick="exit()">退出登录</a></li>
            </ul>
        </div>
      <!-- 左边tree页面 -->
      <input type="hidden" id="menuHid" value="${menuHid }"> 
        <div class="layui-side layui-bg-black">
            <div class="layui-side-scroll ">
                <div id="demo" ></div>
            </div>
        </div>
        <!-- 选项卡要显示的地方 -->
        <div class="layui-body">
            <div class="layui-tab" lay-filter="tabs" lay-allowClose="true">
                <ul class="layui-tab-title">
                </ul>
                <div class="layui-tab-content">
                </div>
            </div>
        </div>
        <div class="layui-footer" align="center" >
            <!-- 底部固定区域 -->
        </div>
    </div>

    UserAction

    public class UserAction extends ActionSupport {
        private UserDao userDao=new UserDao();
        /**
         * 登录
         * @param req
         * @param resp
         * @return
         */
        public String login(HttpServletRequest req,HttpServletResponse resp){
            try {
                List<Map<String, Object>> list=this.userDao.list(req.getParameterMap(), null);
                if(list!=null&&list.size()>0) {
                    List<Map<String, Object>> listMenu=this.userDao.listMenu(req.getParameter("uid"), null);
                    StringBuilder sb=new StringBuilder();
                    for (Map<String, Object> map : listMenu) {
                        sb.append(","+map.get("menuId"));
                    }
                    // ,001,002
                    req.setAttribute("menuHid", sb.substring(1));
                }else {
                    return"login";
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }     
            return "index";
        }    
    }

    MenuAction

    package com.liuwenwu.web;
    import java.util.List;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.liuwenwu.dao.MenuDao;
    import com.liuwenwu.entity.TreeNode;
    import com.liuwenwu.util.ResponseUtil;
    import com.zking.framework.ActionSupport;
    
    public class MenuAction extends ActionSupport {
        private MenuDao menuDao =new MenuDao();
    
        public String treeMenu(HttpServletRequest req,HttpServletResponse resp) {
            try {
                List<TreeNode> list=this.menuDao.list(req.getParameterMap(), null);
                ObjectMapper om=new ObjectMapper();
                //将LIST集合转换为json串
                String jsonStr=om.writeValueAsString(list);
                ResponseUtil.write(resp, jsonStr);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }    
            return null;    
        }
    }

    index.js

    $(function () {
        $.ajax({
            type: "post",
            url:'menuAction.action?methodName=treeMenu&&menuHid='+$("#menuHid").val(),
            dataType: "json",
            success: function (data) {
                console.info(data);
                layui.tree({
                    elem: '#demo',// 传入元素选择器
                    nodes: data,
                    click: function (node) {// 点击tree菜单项的时候
                        var element = layui.element;
                        var exist = $("li[lay-id='" + node.id + "']").length;//判断是不是用重复的选项卡
                        if (exist > 0) {
                            element.tabChange('tabs', node.id);// 切换到已有的选项卡
                        } else {
                            if (node.attributes.menuURL != null && node.attributes.menuURL != "") {// 判断是否需要新增选项卡
                                element.tabAdd(
                                    'tabs',
                                    {
                                        title: node.name,
                                        content: '<iframe   scrolling="yes" frameborder="0" src=" '
                                        + node.attributes.menuURL
                                        + ' " width="100%" height="100%"></iframe>'// 支持传入html
                                        ,
                                        id: node.id
                                    });
                                element.tabChange('tabs', node.id);
                            }
                        }
                    }
                });
            }
        });
    })

    二级权限树形菜单写完以后 是对数据的展示和增删改查

    book.jsp  展示界面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/layui/css/layui.css">   
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/static/js/layui/css/index.css">  
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/layui.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/layui.all.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/jquery-3.3.1.js"></script> 
    <title>Insert title here</title>
    </head>
    
    
    <input type="hidden"  id="dz" value="${pageContext.request.contextPath}" >
    
    <blockquote class="layui-elem-quote">
    <!-- 搜索 -->
     <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">书籍名称</label>
            <div class="layui-input-inline">
                <input type="text" id='book_name' name="book_name" lay-verify="required" placeholder="请输入书籍名" autocomplete="true" class="layui-input">
            </div>
            <button class="layui-btn layui-btn-normal layui-btn-radius" data-type="reload"><i class="layui-icon">&#xe615;</i>查询</button>
            <button class="layui-btn layui-btn-normal"   data-type="add">新建</button>
        </div>
    </div>   
    </blockquote>
    <!-- 展示数据表格 -->
    <table class="layui-hide" id="test" lay-filter="test"></table>
    
    <!--行内样式按钮   -->
    <script type="text/html" id="lineBtns">
          <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon">&#xe642;</i>编辑</a>
         <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
    
    <!--弹出层  -->
         <div class="site-text" style="margin: 5%; display: none" id="box1"  target="test123">
            <form class="layui-form layui-form-pane" onsubmit="return false" id="book">
                <div class="layui-form-item"> 
                   <label class="layui-form-label"> 书本名</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="book_name2"  name=book_name><br>
                    </div>
                    <label class="layui-form-label"> 书本拼音</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="book_name_pinyin"  name=book_name_pinyin><br>
                    </div>
                    <label class="layui-form-label"> 书本类别ID</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="book_category_id"  name=book_category_id><br>
                    </div>
                    <label class="layui-form-label"> 书本作者</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="book_author"  name=book_author><br>
                    </div>
                    <label class="layui-form-label"> 书本价格</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="book_price"  name=book_price><br>
                    </div>
                    <label class="layui-form-label"> 书本出版社</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="publishing"  name=publishing><br>
                    </div>
                     <label class="layui-form-label"> 书本简介</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"  id="book_desc"  name=book_desc><br>
                    </div>
                </div>
            </form>
        </div> 
    <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/layui/book.js"></script>  
    </body>
    </html>

    book.js

    layui.use(['table','layer','form'],function(){
        var data=document.getElementById("dz").value;
        var table =layui.table;
        var layer=layui.layer;
        var form = layui.form;
        table.render({
            elem:'#test',
            url:data+'/bookAction.action?methodName=query',
            method:'post',
            cols:[[
                {field:'book_id',title:'书本ID',100,height:80},    
                {field:'book_name',title:'书本名称',100,height:80}, 
                {field:'book_name_pinyin',title:'书本拼音',100,height:80},  
                {field:'book_category_name',title:'书本类型',100,height:80},  
                {field:'book_author',title:'书本作者',100,height:80},  
                {field:'book_price',title:'书本价格',100,height:80},  
                {field:'book_image',title:'书本图片',100,height:80},  
                {field:'publishing',title:'书本出版社',100,height:80},  
                {field:'book_desc',title:'书本简介',100,height:80},  
                {field:'zt_name',title:'书本状态',100,height:80},  
                {field:'deploy_datetime',height:80, 300, title: '上架时间',templet:"<div>{{layui.util.toDateString(d.deploy_datetime, 'yyyy-MM-dd HH:mm:ss')}}</div>"},
                {field:'sales_volume',title:'书本销量',100,height:80}, 
                {fixed: 'right', title:'操作', toolbar: '#lineBtns', 150}
            ]],
            page:'true',
            id: 'testReload'
        });
        //上方菜单操作栏(查询、以及  增加  按钮  )
        var $ = layui.$, active = {
                //查询
                reload: function () {
                    var name = $('#book_name');//书籍名称 根据 id来取值
                    console.log(name.val());
                    // 执行重载
                    table.reload('testReload', {
                        page: {
                            curr: 1
                            // 重新从第 1 页开始
                        },
                        where: {
                            key: 'book_name',
                            book_name: name.val(),
                        }
                    });
                }, add: function () { //添加
                    layer.open({//弹出框
                        type: 1,
                        title: '添加书本',
                        maxmin: true,
                        shadeClose: true, //点击遮罩关闭层
                        area: ['80%', '80%'],
                        content: $('#box1'),
                        btn: ['确定', '取消'],
                        yes: function (index, layero) {//确定执行函数
                            console.log(layero);
                            //执行添加方法
                            $.getJSON(data+"/bookAction.action?methodName=addBook", {
                                book_name: $("#book_name2").val(),
                                book_name_pinyin: $("#book_name_pinyin").val(),
                                book_category_id: $("#book_category_id").val(),
                                book_author: $("#book_author").val(),
                                book_price: $("#book_price").val(),
                                publishing: $("#publishing").val(),
                                book_desc: $("#book_desc").val()
                                
                            }, function (data) {
                                /*根据后台返回的参数来进行判断  */
                                  if (data >  0) {
                                      //弹出提示层
                                      layer.alert('添加成功', {icon: 1, title: '提示'}, function (i) {
                                          layer.close(i);
                                          layer.close(index);//关闭弹出层
                                          $("#book")[0].reset()//重置form
                                      })
                                      //重载表格
                                      table.reload('testReload', {
                                          page: {
                                              curr: 1// 重新从第 1 页开始
                                          }
                                      })
                                  } else{
                                      //提示添加失败
                                      layer.msg('添加失败')
                                  }
                              })
    
                          }, cancel: function (index, layero) {//取消
                              //当点击取消按钮
                              $("#book")[0].reset()//重置form  根据id
                              layer.close(index)
                          }
                      });
                  }
          }
        $('.layui-form .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        
        /*表格 行内操作(编辑  以及  删除 按钮操作)  */
            table.on('tool(test)', function(obj){
             var data = obj.data; //获得当前行数据
             var urlex=document.getElementById("dz").value;
             var tr=obj.tr//活动当前行tr 的  DOM对象
             console.log(data);
             var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
             if(layEvent === 'del'){ //删除
                 layer.confirm('确定删除吗?',{title:'删除'}, function(index){
                     //向服务端发送删除指令og
                     $.getJSON(urlex+'/bookAction.action?methodName=remove',{book_id: data.book_id}, function(ret){
                             layer.close(index);//关闭弹窗
                             table.reload('testReload', {//重载表格
                                 page: {
                                     curr: 1
                                     // 重新从第 1 页开始
                                 }
                             })
                     });
                     layer.close(index);
                 });
             } else if(layEvent === 'edit'){ //编辑
                 layer.open({
                     type: 1 //Page层类型
                     ,skin: 'layui-layer-molv'
                     ,area: ['380px', '270px']
                     ,title: ['编辑书本信息','font-size:18px']
                     ,btn: ['确定', '取消'] 
                     ,shadeClose: true
                     ,shade: 0 //遮罩透明度
                     ,maxmin: true //允许全屏最小化
                     ,content:$('#box1')  //弹窗id
                     ,success:function(layero,index){
                         $('#book_name2').val(data.book_name);
                         $('#book_name_pinyin').val(data.book_name_pinyin);
                         $('#book_category_id').val(data.book_category_id);
                         $('#book_author').val(data.book_author);
                         $('#book_price').val(data.book_price);
                         $('#publishing').val(data.publishing);
                         $('#book_desc').val(data.book_desc);
                     },yes:function(index,layero){
                          $.getJSON(urlex+'/bookAction.action?methodName=edit',{
                              book_name: $('#book_name2').val(),
                              book_name_pinyin: $('#book_name_pinyin').val(),
                              book_category_id: $('#book_category_id').val(),
                              book_author: $('#book_author').val(),
                              book_price: $('#book_price').val(),
                              publishing: $('#publishing').val(),
                              book_desc: $('#book_desc').val(),
                              book_id: data.book_id,
                          },function(data){
                          //根据后台返回的参数,来进行判断
                              if(data>0){
                                  layer.alert('编辑成功',{icon:1,title:'提示'},function(i){
                                      layer.close(i);
                                      layer.close(index);//关闭弹出层
                                      $("#book")[0].reset()//重置form
                                  })
                                  table.reload('testReload',{//重载表格
                                      page:{
                                          curr:1
                                      }
                                  })
                              }
                          });
                     }
                 });
             }
          });
    })

    BookDao

    package com.liuwenwu.dao;
    import java.sql.SQLException;
    import java.util.List;
    import java.util.Map;
    import com.liuwenwu.util.JsonBaseDao;
    import com.liuwenwu.util.JsonUtils;
    import com.liuwenwu.util.PageBean;
    import com.liuwenwu.util.StringUtils;
    
    public class BookDao extends JsonBaseDao{
        /**
         * 查询未上架
         * @param paMap
         * @param pageBean
         * @return
         * @throws SQLException 
         * @throws IllegalAccessException 
         * @throws InstantiationException 
         */
        public List<Map<String, Object>> query(Map<String, String[]> paMap,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
            String sql="SELECT * FROM (
    " + 
                    "SELECT a.`book_id`,a.`book_name`,a.`book_name_pinyin`,b.`book_category_name`,a.`book_author`,a.`book_price`,a.`book_image`,a.`publishing`,a.`book_desc`,c.`zt_name`,a.`deploy_datetime`,a.`sales_volume` FROM t_book a INNER JOIN t_book_category b INNER JOIN t_book_zt c ON a.book_category_id=b.book_category_id AND a.`book_state`=c.`zt_id`) a
    " + 
                    "WHERE a.zt_name='未上架'";
            String uname = JsonUtils.getParamVal(paMap, "book_name");
            if(StringUtils.isNotBlank(uname)) {
                sql = sql+"  AND a.book_name LIKE '%"+uname+"%'";
            }
            return super.executeQuery(sql, pageBean);
        } 
        
        /**
         * 新增书本方法
         * @param paMap
         * @return
         * @throws NoSuchFieldException
         * @throws SecurityException
         * @throws IllegalArgumentException
         * @throws IllegalAccessException
         * @throws SQLException
         */
        public int addBook(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
            String sql="INSERT INTO t_book (book_name,book_name_pinyin,book_category_id,book_author,book_price,publishing,book_desc) VALUES (?,?,?,?,?,?,?)";  
            return super.executeUpdate(sql, new String[] {"book_name","book_name_pinyin","book_category_id","book_author","book_price","publishing","book_desc"}, paMap);
        }
        
        /**
         * 修改的方法
         * @param paMap
         * @return
         * @throws NoSuchFieldException
         * @throws SecurityException
         * @throws IllegalArgumentException
         * @throws IllegalAccessException
         * @throws SQLException
         */
        public int edit(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
            String sql="update t_book set book_name=?,book_name_pinyin=?,book_category_id=?,book_author=?,book_price=?,publishing=?,book_desc=? where book_id=?";
            return super.executeUpdate(sql, new String[] {"book_name","book_name_pinyin","book_category_id","book_author","book_price","publishing","book_desc","book_id"}, paMap);
        }
        
        /**
         * 删除方法
         * @param paMap
         * @return
         * @throws NoSuchFieldException
         * @throws SecurityException
         * @throws IllegalArgumentException
         * @throws IllegalAccessException
         * @throws SQLException
         */
        public int remove(Map<String, String[]> paMap) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
            String sql="delete from t_book where book_id=?";
            return super.executeUpdate(sql, new String[] {"book_id"}, paMap);
        }    
    }

    BookAction  

    package com.liuwenwu.web;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.liuwenwu.dao.BookDao;
    import com.liuwenwu.util.PageBean;
    import com.liuwenwu.util.ResponseUtil;
    import com.zking.framework.ActionSupport;
    
    public class BookAction extends ActionSupport{
        private BookDao bookDao=new BookDao();
        /**
         * 查询请求
         * @param req
         * @param resp
         * @return
         */
        public String query(HttpServletRequest req,HttpServletResponse resp) {
            try {
                PageBean pageBean=new PageBean();
                pageBean.setRequest(req);
                List<Map<String, Object>> list=this.bookDao.query(req.getParameterMap(), pageBean);
                ObjectMapper om=new ObjectMapper();
                Map<String, Object> map=new HashMap<>();
                map.put("code", 0);
                map.put("count", pageBean.getTotal());
                map.put("data", list);
                ResponseUtil.write(resp, om.writeValueAsString(map));
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            return null;    
        }
        
        /**
         * 增加
         * @param req
         * @param resp
         * @return
         */
        public String addBook(HttpServletRequest req,HttpServletResponse resp) {
            try {
                int n=this.bookDao.addBook(req.getParameterMap());
                ResponseUtil.write(resp, n);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        
        /**
         * 修改方法
         * @param req
         * @param resp
         * @return
         */
        public String edit(HttpServletRequest req,HttpServletResponse resp){
            try {
                int edit = this.bookDao.edit(req.getParameterMap());
                ObjectMapper om=new ObjectMapper();
                ResponseUtil.write(resp, om.writeValueAsString(edit));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
            
            return null;
        }
        
        /**
         * 删除请求
         * @param req
         * @param resp
         * @return
         */
        public String remove(HttpServletRequest req,HttpServletResponse resp) {
            try {
                int remove=this.bookDao.remove(req.getParameterMap());
                ObjectMapper om=new ObjectMapper();
                ResponseUtil.write(resp, om.writeValueAsString(remove));
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            return null;    
        }    
    }

    mvc.xml的配置

    <?xml version="1.0" encoding="UTF-8"?>
    <config>
        <!-- <action path="/regAction" type="test.RegAction">
            <forward name="failed" path="/reg.jsp" redirect="false" />
            <forward name="success" path="/login.jsp" redirect="true" />
        </action> -->
        
        <action path="/menuAction" type="com.liuwenwu.web.MenuAction">
            <forward name="index" path="/index.jsp" redirect="false" />
        </action>
        
        <action path="/userAction" type="com.liuwenwu.web.UserAction">
            <forward name="index" path="/index.jsp" redirect="false" />
        </action>
        
        <action path="/bookAction" type="com.liuwenwu.web.BookAction">
            <forward name="index" path="/index.jsp" redirect="false" />
        </action>
        
    </config>

  • 相关阅读:
    Codeforces Round #359 (Div. 2) C. Robbers' watch 鸽巢+stl
    poj 3616 Milking Time dp
    UVA 11401
    UVA 11806 Cheerleaders dp+容斥
    Educational Codeforces Round 4 D. The Union of k-Segments 排序
    Codeforces Round #337 (Div. 2) C. Harmony Analysis 数学
    Codeforces Round #337 (Div. 2) B. Vika and Squares 水题
    Codeforces Round #337 (Div. 2) A. Pasha and Stick 水题
    POJ2402/UVA 12050 Palindrome Numbers 数学思维
    UVA 11076 Add Again 计算对答案的贡献+组合数学
  • 原文地址:https://www.cnblogs.com/xiatian3452/p/11254391.html
Copyright © 2020-2023  润新知