IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> 用户管理系统(LayUI+JQuery+SSM)前后端分离开发 -> 正文阅读

[JavaScript知识库]用户管理系统(LayUI+JQuery+SSM)前后端分离开发

自己写的一个简单项目
注释写的很详细,主要是表格的CURD操作,文章结尾放了项目源码,有兴趣的朋友可以下载

功能介绍:

登录功能:启动服务器跳转到登录界面,用户输入正确的账号密码登录到主页面,为避免未登录的用户通过直接访问html文件进入主页面,设置了拦截器进行拦截,提高了项目的安全性。

主页功能:一些常用的操作,如关闭当前页面,退出登录,修改密码等。

表格功能:表格页面是主页面的子页面,主要是对表格的增删查改操作。

1. Html页面

index.jsp

<jsp:forward page="page/login-1.html"></jsp:forward>

登录界面

<script>


        layui.use(['form'], function () {
            var form = layui.form,
                layer = layui.layer;

            // 登录过期的时候,跳出ifram框架
            // if (top.location != self.location) top.location = self.location;

            // 粒子线条背景
            $(document).ready(function(){
                $('.layui-container').particleground({
                    dotColor:'#7ec7fd',
                    lineColor:'#7ec7fd'
                });
            });

            // 进行登录操作
            $("#btn").click(function () {
                if ($("#captcha").val()!="xszg")
                {
                    alert("验证码错误")
                    return ;
                }

                $.ajax(
                    {
                        url: "http://localhost:8888/login",
                        type: "GET",
                        dataType: "json",
                       data:$("#form").serialize(),
                        success: function (data) {
                            if (data.codes=="1")
                            {


                                window.location.href="page/MainInterface.html"
                            }
                          else
                            {
                                alert("账户或密码错误")
                            }
                        }

                    })
                return false;
            })

       })







</script>

主页面

<script>

    layui.use(['jquery', 'layer', 'miniAdmin','miniTongji'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            miniAdmin = layui.miniAdmin,
            miniTongji = layui.miniTongji;

        var options = {
            iniUrl: "../api/init.json",    // 初始化接口
            clearUrl: "../api/clear.json", // 缓存清理接口
            urlHashLocation: true,      // 是否打开hash定位
            bgColorDefault: false,      // 主题默认配置
            multiModule: true,          // 是否开启多模块
            menuChildOpen: false,       // 是否默认展开菜单
            loadingTime: 0,             // 初始化加载时间
            pageAnim: true,             // iframe窗口动画
            maxTabNum: 20,              // 最大的tab打开数量
        };
        miniAdmin.render(options);

        // 百度统计代码,只统计指定域名
        miniTongji.render({
            specific: true,
            domains: [
                '99php.cn',
                'layuimini.99php.cn',
                'layuimini-onepage.99php.cn',
            ],
        });

        $('.login-out').on("click", function () {
            layer.msg('退出登录成功', function () {

                $.ajax(
                    {
                        url: "http://localhost:8888/exitLogin",
                        type: "GET",
                        dataType: "text",
                        success:function (data) {

                            if (data=="OK")
                            {
                               window.location.href="login-1.html";
                            }
                        }
                    }
                )
            });
        });
    });
</script>

表格界面

<script>

 $(function () {

     $.ajax(
         {
             url: "http://localhost:8888/searchList",
             type: "GET",
             dataType: "json",
             success: function (data) {

                 var d=data;
                 layui.use(['form', 'table'], function () {
                     var $ = layui.jquery,
                         form = layui.form,
                         table = layui.table;

                table.render({
                         elem: '#currentTableId',
                         data:d,              //将返回的数据放入表格
                         toolbar: '#toolbarDemo',
                         defaultToolbar: ['filter', 'exports', 'print', {
                             title: '提示',
                             layEvent: 'LAYTABLE_TIPS',
                             icon: 'layui-icon-tips'
                         }],

                         cols: [[     //field的属性值要和返回的json数据的键一样
                             {type: "checkbox", width: 50},
                             {field: 'id', width: 80, title: 'ID', sort: true},
                             {field: 'name', width: 80, title: '用户名'},
                             {field: 'sex', width: 80, title: '性别', sort: true},
                             {field: 'city', width: 80, title: '城市'},
                             {field: 'job', width: 80, title: '职业'},
                             {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"},

                         ]],
                         limits: [10, 15, 20, 25, 50, 100],
                         limit: 15,
                         page: true,
                         skin: 'line',
                         parseData:function (d) {  //layUI表格接受后端数据的格式转换
                             return {
                                 "code": 0, //解析接口状态
                                 "msg": "", //解析提示文本
                                 "count": 100, //数据总条数
                                 "data": d //数据

                             }
                         }
                     });

                     // 监听搜索操作
                     form.on('submit(data-search-btn)', function (data) {
                         var result = JSON.stringify(data.field);

                         if ($("#name").val()==""&&
                             $("#sex").val()==""&&
                             $("#job").val()==""&&
                             $("#city").val()=="")
                         {
                             //搜索全部
                             table.reload('currentTableId', {
                                 url: "http://localhost:8888/searchList",
                                 page: {
                                     curr: 1
                                 }
                                 , where: {

                                 }
                             }, 'data');

                             return false;
                         }
                         else
                         {
                             //搜索关键字
                             table.reload('currentTableId', {
                                 url: "http://localhost:8888/searchKey",
                                 page: {
                                     curr: 1
                                 }
                                 , where: {
                                     Key: result
                                 }
                             }, 'data');

                             return false;
                         }
                     });

                     //复选框监听
                     table.on('checkbox(currentTableFilter)', function (obj) {

                     });



                     /**
                      * toolbar监听事件
                      */
                     table.on('toolbar(currentTableFilter)', function (obj) {
                         if (obj.event === 'add') {  // 监听添加操作
                             var index = layer.open({
                                 title: '添加用户',
                                 type: 2,
                                 shade: 0.2,
                                 maxmin:true,
                                 shadeClose: true,
                                 area: ['100%', '100%'],
                                 content: '../page/table/add.html',
                                 success:function (layero, index) {

                                 }
                             });
                             $(window).on("resize", function () {
                                 layer.full(index);
                             });
                         } else if (obj.event === 'delete') {  // 监听删除操作
                             var checkStatus = table.checkStatus('currentTableId');
                             //必须转换为json类型,否则后端无法识别
                             var result= JSON.stringify(checkStatus.data)

                             layer.close(index);
                             table.reload('currentTableId', {
                                 url: "http://localhost:8888/deleteCustomer",
                                 page: {
                                     curr: 1
                                 }
                                 , where: {
                                     trData: result
                                 }
                             }, 'data');

                             return false;
                         }
                         else if (obj.event === 'save')
                         {
                             //关闭单元格编辑
                            $(".layui-table").find('td').data('edit', false);
                             //判断是否选中修改数据的行

                             var checkStatus = table.checkStatus('currentTableId');
                             var result= JSON.stringify(checkStatus.data) //得到json数组型字符串[{name:"xxx"}]

                             table.reload('currentTableId', {
                                 url: "http://localhost:8888/updateCustomer",
                                 page: {
                                     curr: 1
                                 }
                                 , where: {
                                     Key: result
                                 }
                             }, 'data');

                             return false;
                         }
                     });


                   //监听编辑和删除操作
                     table.on('tool(currentTableFilter)', function (obj) {
                         var data = obj.data;
                         if (obj.event === 'edit') {

                             //开启单元格编辑
                             $(".layui-table").find('td').data('edit', true);


                         } else if (obj.event === 'delete') {
                             layer.confirm('确定删除该用户吗', function (index) {
                                 var checkStatus = table.checkStatus('currentTableId');
                                 //必须转换为json类型,否则后端无法识别
                              var result= JSON.stringify(checkStatus.data)

                                 layer.close(index);
                                 table.reload('currentTableId', {
                                     url: "http://localhost:8888/deleteCustomer",
                                     page: {
                                         curr: 1
                                     }
                                     , where: {
                                          trData: result
                                     }
                                 }, 'data');

                                 return false;


                             });
                         }
                     });

                 })


             }}
     )


 })


</script>

修改密码页面

<script>
    layui.use(['form','miniTab'], function () {
        var form = layui.form,
            layer = layui.layer,
            miniTab = layui.miniTab;
            $ = layui.$;  //layui内置jquery
        //监听提交
        form.on('submit(saveBtn)', function (data) {
            var result=JSON.stringify(data.field);
            var  object=JSON.parse(result); //转换为json对象
            if (object.new_password!=object.again_password)
            {
                alert("两次输入的密码不一致,请仔细核对");

                return false;
            }
            var index = layer.confirm("确定修改密码吗?", {
                title: '提示'
            }, function () {
                layer.close(index);
                $.ajax(
                    {
                        url:"http://localhost:8888/updateUserPassword",
                        type:"get",
                        dataType:"text",
                        data:{formKey:result},
                        success:function (data) {

                            if (data=="OK")
                            {
                                alert("修改成功")
                                // // 在iframe层关闭当前tab方法

                                miniTab.deleteCurrentByIframe();

                            }
                            else if (data=="ERROR")
                            {
                                alert("修改失败");
                                location.reload(); //刷新当前页面
                            }
                        }
                    }
                )





                return false;






            });
            return false;
        });

    });
</script>

添加页面

<script>
    //使用form和table模块
    layui.use(['form'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.$;

        //监听提交
        form.on('submit(saveBtn)', function (data) {
           var result=JSON.stringify(data.field)
            var index = layer.confirm("确定添加该用户吗?", {
                title: '提示'
            }, function () {
                //确定执行该方法

                layer.close(index); //关闭提示窗口
                var iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex); //关闭当前窗口


            $.ajax(
                {
                    url:"http://localhost:8888/addCustomer",
                    type:"get",
                    dataType:"text",
                    data:{formKey:result},
                    success:function (data) {

                          if (data=="OK")
                          {
                              parent.location.reload(); //父页面刷新
                          }
                          else
                          {
                              alert("添加失败")
                          }
                    }
                }
            )
          return false;






            });
          return false;

        });

    });
</script>

404页面

<script>
    function randomNum() {
        return Math.floor(Math.random() * 9) + 1;
    }

    var loop1, loop2, loop3, time = 30, i = 0, number;
    loop3 = setInterval(function () {
        if (i > 40) {
            clearInterval(loop3);
            document.querySelector('.thirdDigit').textContent = 4;
        } else {
            document.querySelector('.thirdDigit').textContent = randomNum();
            i++;
        }
    }, time);
    loop2 = setInterval(function () {
        if (i > 80) {
            clearInterval(loop2);
            document.querySelector('.secondDigit').textContent = 0;
        } else {
            document.querySelector('.secondDigit').textContent = randomNum();
            i++;
        }
    }, time);
    loop1 = setInterval(function () {
        if (i > 100) {
            clearInterval(loop1);
            document.querySelector('.firstDigit').textContent = 4;
        } else {
            document.querySelector('.firstDigit').textContent = randomNum();
            i++;
        }
    }, time);
</script>

2.Control层

package Control;

import Service.CustomerService;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.xerces.internal.xs.XSAttributeUse;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import po.Customer;
import po.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Key;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CustomerControl {
    @Autowired
    private CustomerService customerService;
    Gson gson=new Gson();
    @GetMapping(value = "/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {

      String username=request.getParameter("username");
      String password=request.getParameter("password");

       Map <String,String> map=new HashMap<String, String>();
     User user=customerService.findUser(username,password);
      map.put("codes","0");//0代表未匹配成功
     if (user!=null)
     {
         //用户登录成功设置会话属性,拦截器根据会话属性判断用户是否登录
         request.getSession().setAttribute("user_information",user);
         map.put("codes","1"); //1代表匹配成功

      response.getWriter().write(gson.toJson(map));
      return;
     }


    response.getWriter().write(gson.toJson(map));
   }

   @RequestMapping("/searchList")
    public void searchList(HttpServletResponse response) throws IOException {

        List<Customer> list=customerService.findCustomerAll();

       response.setContentType("text/html;charset=UTF-8");
      response.getWriter().write(gson.toJson(list));
   }

   @RequestMapping("/searchKey")
    public void searchKey(HttpServletResponse response,HttpServletRequest request) throws IOException {
       String key=request.getParameter("Key");
       //将json字符串转换为JsonObject对象,{name:“1”}一个对象 [{name:"1"},{name:"2"}]多个对象用jsonArray
       JsonObject object=gson.fromJson(key,JsonObject.class);//JsonObject本质为Map<String,Object>

       for (String keys:object.keySet()
            ) {
           //第一个不为空的搜索关键字作为参数,toString()不能将JsonElement转换为string类型
           if (!(object.get(keys).getAsString().equals("")))  //第一个不为空的搜索关键字作为参数,toString()不能讲JsonElement
           {

              key=object.get(keys).getAsString();

           }
       }
      List<Customer> list=customerService.findCustomerByKey(key);
       response.setContentType("text/html;charset=UTF-8");

      response.getWriter().write(gson.toJson(list));


   }

   @RequestMapping(value = "/deleteCustomer")
   public void delete(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String Key=request.getParameter("trData");
        int i=0;
     //转换类型需要参考json数据,[{"id":"001","name":"xx"}] 数组型json数据只能转化为jsonArray
      JsonArray array=gson.fromJson(Key,JsonArray.class);

      for (int index=0;index<array.size();index++)
      {

          Key=array.get(index).getAsJsonObject().get("id").getAsString();
          i= customerService.deleteCustomer(Key);
      }
     List<Customer> list=customerService.findCustomerAll();
              if (i>=1)
          response.getWriter().write(gson.toJson(list));

   }

   @RequestMapping(value = "/addCustomer")
    public void add(HttpServletRequest request,HttpServletResponse response) throws IOException {
      String formValue=request.getParameter("formKey");
       Customer customer=gson.fromJson(formValue,Customer.class);

       int i=customerService.insertCustomer(customer);
       if (i>=1)
           response.getWriter().write("OK");
       else
           response.getWriter().write("Error");

   }

   @RequestMapping(value = "/updateCustomer")
    public void updateCustomer(HttpServletRequest request,HttpServletResponse response) throws IOException {
       int i=0;
       String jsonStr;
       String json=request.getParameter("Key");
      Customer customer;

       JsonArray array=gson.fromJson(json,JsonArray.class);

       for (int index=0;index<array.size();index++)
       {

          jsonStr=array.get(index).getAsJsonObject().toString();

           customer=gson.fromJson(jsonStr,Customer.class);

         i=customerService.updateCustomer(customer);

       }


       List<Customer> list=customerService.findCustomerAll();
       if (i>=1)
           response.getWriter().write(gson.toJson(list));
   }

   @RequestMapping(value ="/updateUserPassword" )
    public void updateUserPassword(HttpServletRequest request,HttpServletResponse response) throws IOException {
          String json=request.getParameter("formKey");
          int i=0;
          //得到登录的用户账号信息
        User user= (User) request.getSession().getAttribute("user_information");

          JsonObject object=gson.fromJson(json,JsonObject.class);
          i=  customerService.updateUserPassword(user.getUserid(),object.get("old_password").getAsString(),object.get("new_password").getAsString());

          if (i>=1)
              response.getWriter().write("OK"); //修改成功
          else
              response.getWriter().write("ERROR"); //修改失败
   }

   @RequestMapping(value = "/exitLogin")
    public void exit(HttpServletRequest request,HttpServletResponse response) throws IOException {
       request.getSession().invalidate(); //会话销毁
       response.getWriter().write("OK");
   }

}

3.登录拦截器

package interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
          String url=httpServletRequest.getRequestURI();

          if (url.indexOf("MainInterface.html")>=0)
          {

            if (httpServletRequest.getSession().getAttribute("user_information")==null)
            {
                return false; //拦截
            }
          }
          return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

4.源码下载链接
https://pan.baidu.com/s/1wMQLtDpGjSaPRZyflww1uA
提取码:xszg

  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-08-05 17:16:33  更:2021-08-05 17:17:09 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/17 14:38:26-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码