天天看點

使用者管理系統(LayUI+JQuery+SSM)前後端分離開發

自己寫的一個簡單項目

注釋寫的很詳細,主要是表格的CURD操作,文章結尾放了項目源碼,有興趣的朋友可以下載下傳

功能介紹:

登入功能:啟動伺服器跳轉到登入界面,使用者輸入正确的賬号密碼登入到首頁面,為避免未登入的使用者通過直接通路html檔案進入首頁面,設定了攔截器進行攔截,提高了項目的安全性。

首頁功能:一些常用的操作,如關閉目前頁面,登出,修改密碼等。

表格功能:表格頁面是首頁面的子頁面,主要是對表格的增删查改操作。

1. Html頁面

index.jsp

登入界面

<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