列表页面实现是几种方式(前后端)

  • Post author:
  • Post category:其他


方式一、springboot+theymeleaf+jquery+ajax+bootstrap

这种方式呢就是前后台不分离,table数据是通过theymeleaf来显示,后台model赋值。更新和保存通过ajax请求后台,form方式提交。

controller

package com.xy.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xy.config.MySqlParam;
import com.xy.model.Book;
import com.xy.system.dao.UserMapper;
import com.xy.system.model.vo.UserSearchVo;
import com.xy.system.model.vo.UserVo;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

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

@Controller
public class TestController {
    @Autowired
    private UserMapper userMapper;
    @RequestMapping("/testList")
    public String test(@RequestParam Map<String, String> param, UserSearchVo userSearch, Model model){
        String userNameQry = MapUtils.getString(param,"userNameQry");
        MySqlParam<Book> mySqlParam = new MySqlParam<>();
        mySqlParam.likeIfNotNull("user_name",userNameQry);

        if (param.size() == 0 || param.get("pageNum").isEmpty()) {
            param.put("pageNum", "1");
        }
        int pageSize = 3;
        int pageNum = Integer.valueOf(param.get("pageNum"));
        PageHelper.startPage(pageNum, pageSize);
        List<UserVo> Users = userMapper.selectList(mySqlParam);
        PageInfo<UserVo> pageInfo = new PageInfo<>(Users);
        model.addAttribute("userList", pageInfo.getList());
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("userNameQry", userNameQry);
       return "/testList";
    }
}





UserController.java

package com.xy.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.xy.config.ResponseUtils;
import com.xy.system.config.PageDataResult;
import com.xy.system.dao.UserMapper;
import com.xy.system.model.User;
import com.xy.system.model.vo.LoginVo;
import com.xy.system.model.vo.UserSearchVo;
import com.xy.system.service.UserService;
import com.xy.system.util.Md5Util;
import com.xy.util.CookieUtil;
import com.xy.util.JWTUtil;
import com.xy.vo.ResultVO;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Title: UserController
 * @Description: 系统用户管理
 * @author: youqing
 * @version: 1.0
 * @date: 2018/11/20 15:17
 */
@Controller
@RequestMapping("user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request, HttpServletResponse response, LoginVo loginDTO, HttpSession session){
        logger.info("进行登陆");
        Map<String,Object> data = new HashMap();
        // 使用 shiro 进行登录
//        Subject subject = SecurityUtils.getSubject();

        String userName = loginDTO.getUsername().trim();
        String password = loginDTO.getPassword().trim();
        String rememberMe = loginDTO.getRememberMe();
        String host = request.getRemoteAddr();

        // 调用数据层
        User user = userService.findByUserName(userName);
        String encryptPwd = Md5Util.encrypt(password);
        if(user == null){
            data.put("code",0);
            data.put("message","用户名不存在");
            logger.info(user.getUserId()+"登陆失败");
        } else if(encryptPwd.equals(user.getSysUserPwd())){
            session.setAttribute("user", user.getUserId());
            data.put("code",1);
            data.put("url","/home3");
            data.put("message","登陆成功");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId",user.getUserId());
            jsonObject.accumulateAll(data);
            logger.info(user.getUserId()+"登陆成功");
            CookieUtil.set(response,"token", JWTUtil.genToken(jsonObject),false);
            CookieUtil.set(response,"userId", user.getUserId(),false);
            CookieUtil.set(response,"userName", user.getUserName(),false);
        }else{
            data.put("code",0);
            data.put("message","用户名或密码错误");
            logger.info(user.getUserId()+"登陆失败");
        }
        return data;
    }

    /**
     *
     * 功能描述: 跳到系统用户列表
     *
     * @param:
     * @return:
     * @auther: youqing
     * @date: 2018/11/21 13:50
     */
    @RequestMapping("/userManage")
    public String userManage() {
        return "/user/userManage";
    }

    /**
     *
     * 功能描述: 分页查询用户列表
     *
     * @param:
     * @return:
     * @auther: youqing
     * @date: 2018/11/21 11:10
     */
    @RequestMapping(value = "/getUserList", method = RequestMethod.POST)
    @ResponseBody
    public PageDataResult getUserList(@RequestParam("pageNum") Integer pageNum,
                                      @RequestParam("pageSize") Integer pageSize,/*@Valid PageRequest page,*/ UserSearchVo userSearch) {
        /*logger.info("分页查询用户列表!搜索条件:userSearch:" + userSearch + ",pageNum:" + page.getPageNum()
                + ",每页记录数量pageSize:" + page.getPageSize());*/
        PageDataResult pdr = new PageDataResult();
        try {
            if(null == pageNum) {
                pageNum = 1;
            }
            if(null == pageSize) {
                pageSize = 10;
            }
            // 获取用户列表
            pdr = userService.getUserList(userSearch, pageNum ,pageSize);
            logger.info("用户列表查询=pdr:" + pdr);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户列表查询异常!", e);
        }
        return pdr;
    }

    /**
     *
     * 功能描述: 新增和更新系统用户
     *
     * @param:
     * @return:
     * @auther: youqing
     * @date: 2018/11/22 10:14
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateUser(User user) {
        logger.info("设置用户[新增或更新]!user:" + user);
        Map<String,Object> data = new HashMap();
        if(user.getId() == null){
            data = userService.addUser(user);
        }else{
            data = userService.updateUser(user);
        }
        return data;
    }

    /**
     *
     * 功能描述: 删除/恢复 用户
     *
     * @param:
     * @return:
     * @auther: youqing
     * @date: 2018/11/22 11:59
     */
    @RequestMapping(value = "/updateUserStatus", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateUserStatus(@RequestParam("id") Integer id,@RequestParam("status") Integer status) {
        logger.info("删除/恢复用户!id:" + id+" status:"+status);
        Map<String, Object> data = new HashMap<>();
        if(status == 0){
            //删除用户
            data = userService.delUser(id,status);
        }else{
            //恢复用户
            data = userService.recoverUser(id,status);
        }
        return data;
    }
    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String expireToken = JWTUtil.getExpireToken();
        CookieUtil.set(response,"token", expireToken,false);
        return "redirect:/login";
    }

    @RequestMapping("/userList")
    public String userList(@RequestParam Map<String, String> map,UserSearchVo userSearch,Model model){
        if (map.size() == 0 || map.get("pageNum").isEmpty()) {
            map.put("pageNum", "1");
        }
        int pageSize = 5;
        int pageNum = Integer.valueOf(map.get("pageNum"));
        PageInfo pageInfo = userService.getUserList2(userSearch,pageNum,pageSize);
        model.addAttribute("userList", pageInfo.getList());
        model.addAttribute("pageInfo", pageInfo);
        return "/system/userList";
    }
    @RequestMapping("/qryUserList")
    @ResponseBody
    public String qryUserList(@RequestParam Integer currentPage,Model model){
        List<User> list = userService.selectList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        jsonObject.put("total",list.size());
        return ResponseUtils.success(list);
    }

    @GetMapping("/queryByUserId")
    @ResponseBody
    public User queryByUserId(Integer id, Model model){
        ResultVO resultVO = new ResultVO();
        QueryWrapper<User> queryWrapper =  new QueryWrapper();
        queryWrapper.eq("id",id);
        User bean = userService.selectUser(queryWrapper);
//        model.addAttribute("bookEdit",book1);
        return bean;
    }

    @GetMapping("/userDel/{userId}")
    @ResponseBody
    public int deleteBook(@PathVariable("userId") Integer userId){
        User bean = new User();
        bean.setId(userId);
        return userMapper.deleteById(bean);
    }
}

testList.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--4. 添加bootstrap依赖-->
<!--
    <link rel="stylesheet" href="/plugin/jquery/pagination/v2/jquery.pagination.css">
-->
    <script src="/js/includeJs_3rd.js"></script>
    <script src="/js/includeCss_3rd.js"></script>
   <!--用到  jquery  bootstrap-->
</head>
<body>
<div class="modal-body">
    <form id="queryForm"  class="form-horizontal" method="post">
        <div>
            <div class="row">
                <label  class="queryRowLabel">书名:</label>
                <input class="form-control queryInput" id="userNameQry" name="userNameQry" th:value="${userNameQry}">

                <label  class="queryRowLabel">作者:</label>
                <input class="form-control queryInput"  id="author" name="author" >
                <button class="btn btn-primary btn-sm" onclick="qryUser()">查 询</button>
            </div>
        </div>
    </form>
</div>
<div class="container1">
    <!--<h2>基础表格</h2>-->
    <div class="margin-top20 margin-left10">
        <div class="title_small"></div>
        <span>图书检索列表</span>
        <a href="#" class="btn btn-info btn-sm floatright margin-bottom10" data-toggle="modal" data-target="#myModal"
           @click="user={};title='添加书籍'">新增</a>
    </div>
    <table class="table table-bordered table-hover">
        <thead>
        <tr>
            <th>编号</th>
            <th>名称</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="user:${userList}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.userName}"></td>
            <td>
                <a href="#" th:onclick="'queryByUserId('+${user.id}+');'" class="btn btn-success btn-sm"
                   data-toggle="modal" data-target="#myModal"
                   @click="user=bk;title='修改'">修改</a>
                <a href="#" class="btn btn-danger btn-sm" th:onclick="'delUser('+${user.id}+');'">删除</a>
            </td>
        </tr>
        </tbody>
    </table>

    <div class="modal fade" id="myModal">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">信息</h4>
                <!--    &#45;&#45;${bookEdit.userId}-->
                </div>
                <div class="modal-body">
                    <form id="editBookForm" class="form-horizontal" method="post">
                        <input type="hidden" id="id" name="id" v-model="user.id">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">登录账号:</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="userId" name="userId"
                                       v-model="user.userId"
                                       placeholder="登录名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">用户名:</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="userName" name="userName"
                                       v-model="user.userName"
                                       placeholder="姓名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label ">手机号:</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="userPhone" name="userPhone"
                                       v-model="user.userPhone"
                                       placeholder="手机号">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭(C)</button>
                    <button type="button" class="btn btn-primary" onclick="save()">保存(S)</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="pagination">
<div  class="dzm-pagination-container">
    <a><b th:text="'共 '+ ${pageInfo.getTotal()}+ ' 条'"></b></a>
    <a class="dzm-pagination-page-item" th:href="@{/testList(pageNum=${pageInfo.getNavigateFirstPage()})}"  >首页</a>
    <a class="dzm-pagination-page-item" th:if="${pageInfo.isHasPreviousPage()} == true" th:href="@{/testList(pageNum=${pageInfo.getPrePage()})}"  >上一页</a>
    <a class="dzm-pagination-page-item" th:href="@{'/testList?pageNum=' + ${i}}"  th:each="i :${#numbers.sequence(pageInfo.getNavigateFirstPage(), pageInfo.getNavigateLastPage())}" th:text="  ${i}"   th:class="${pageInfo.getPageNum() == i}? 'dzm-pagination-page-item active' :' dzm-pagination-page-item' "></a>
    <a class="dzm-pagination-page-item" th:if="${pageInfo.isHasNextPage()} == true" th:href="@{/testList(pageNum=${pageInfo.getNextPage()})}" >下一页</a>
    <a class="dzm-pagination-page-item" th:href="@{/testList(pageNum=${pageInfo.getNavigateLastPage()})}" >尾页</a>
</div>
</div>

    <!--<div id="pagination"></div>-->
</body>
</html>
<script type="text/javascript">
    $(function () {
        // $("#pagination").pagination({
        //     currentPage: 1,
        //     totalPage: 12
        // });

        // getDataList(1);
    });
    function qryUser(){
        let url ="/testList";
        let formData = $("#queryForm").serialize();
        // Object.assign(formData,{pageNum:1});
        requestPost(url, JSON.stringify(formData)).then(function (data) {
            // if(data.code == 200){
            //     window.location.href="/testList";
            // }else{
            //    alert("查询失败!")
            // }
        });
    }


    function delUser(id) {
        let url = "/user/userDel/" + id;
        if (confirm("你确定要删除吗?")) {
            $.get(url, {}, function (data) {
                window.location.href = "/testList";
            });
            requestGet(url, {}).then(function (resp){
                window.location.href = "/testList";
            });
        }
    }
    function save() {
        let id = $("#id").val();
        let formData = $("#editBookForm").serialize();
        let url = "/user/updateUser";
        $.post(url, formData, function (data) {
            $("#myModal").modal('hide');
            window.location.href = "/testList";
        });


    }

    function queryByUserId(id) {
        $.get("/user/queryByUserId", {"id": id}, function (data) {
            let currentForm = $("#editBookForm");  // Get the form
            PopulateUpdateForm(currentForm, data)
        });

    }

</script>

common.js

// $('#header').load(`/common/header.html`)
// $('#footer').load(`/common/footer.html`)



function requestGet(url,data){
    return http(url,"get",data);
}
function requestPost(url,data){
    return http(url,"POST",data);
}
function http(url,method,data){
   return  $.ajax({
        type :method,
        url : url,
        data :data,
        //dataType : "json", //返回类型
        contentType: "application/json;charset=utf-8"
    });
}



function PopulateUpdateForm(currentForm, data) {
    $.each(data, function (key, value) {
// Populate Form data by input Name
        var ctrl = $('[name=' + key + ']', currentForm);
        switch (ctrl.prop("type")) {
            case "radio":
            case "checkbox":
                ctrl.each(function () {
                    if ($(this).attr('value') == value) $(this).attr("checked", value);
                });
                break;
            default:
                ctrl.val(value);
        }
    });
}


$.fn.serializeJson = function () {
    var serializeObj = {};
    var array = this.serializeArray();
    // var str=this.serialize();
    $(array).each(function () { // 遍历数组的每个元素
        if (serializeObj[this.name]) { // 判断对象中是否已经存在 name,如果存在name
            if ($.isArray(serializeObj[this.name])) {
                serializeObj[this.name].push(this.value); // 追加一个值 hobby : ['音乐','体育']
            } else {
                // 将元素变为 数组 ,hobby : ['音乐','体育']
                serializeObj[this.name] = [serializeObj[this.name], this.value];
            }
        } else {
            serializeObj[this.name] = this.value; // 如果元素name不存在,添加一个属性 name:value
        }
    });
    return serializeObj;
};


includeCss_3rd.js
function includeCss(fileName) {
 document.write("<link rel='stylesheet' type='text/css' href='"+ROOT_CONTEXT+fileName+"'/>");
}

document.write("<meta http-equiv='Pragma' content='no-cache'>");
document.write("<meta http-equiv='Cache-Control' content='no-cache'>");
document.write("<meta http-equiv='Expires' content='0'>");


// includeCss("plugins/bootstrap/css/bootstrap.min.css");
/*includeCss("plugin/bootstrap/css/bootstrap.css");*/
<!-- Font Awesome Icons -->
includeCss("css/common.css");

includeCss("plugin/bootstrap/css/bootstrap.css");
includeCss("plugin/jquery/pagination/v2/jquery.pagination.css");
// includeCss("plugin/adminlte/plugin/fontawesome-free/css/all.min.css");
// <!-- Theme style -->
// includeCss("plugin/adminlte/dist/css/adminlte.min.css");
includeJs_3rd.js
var ROOT_CONTEXT= "/";
function includeJs(filename) {  
 document.write("<script type='text/javascript' src='"+ROOT_CONTEXT+filename+"'><\/script>");
}

includeJs("plugin/jquery/jquery-3.6.0.min.js");
includeJs("plugin/bootstrap/js/bootstrap.js");
includeJs("plugin/layer/layer.js");
includeJs("js/common.js");
includeJs("js/menu.js");

// <!-- Bootstrap 4 -->
// includeJs("plugin/bootstrap/4.6.1/js/bootstrap.bundle.min.js")
// includeJs("plugin/bootstrap/js/bootstrap.js")
// <!-- AdminLTE App -->
// includeJs("plugin/adminlte/dist/js/adminlte.min.js")
includeJs("js/common/CookieUtil.js")

common.css

.margin-left10{
    margin-left:10px
}
.margin-top20{
    margin-top:20px
}
.margin-top50{
    margin-top:60px
}
.margin-top60{
    margin-top:60px
}
.margin-bottom10{
    margin-bottom:10px
}
.padding-bottom10{
    padding-bottom:10px
}
.center{
    text-align: center;
}
.width100{
    width: 100%;
}
.margin-auto{
    margin: 0 auto;
}

.width120{
    width: 120px;
}
.width330{
    width: 330px;
}
.floatleft{
    float: left;
}
.floatright{
    float: right;
}

.margin-auto-top60{
    display:flex;
    justify-content: center;/*水平居中*/
    width:100%;
    height:100%;
    margin-top:60px
}
.title_small{
    float:left;
    line-height: 25px;
    height: 25px;
    text-shadow: 2px 2px 3px #222222;
    background: #2B6695;
    padding: 3px;
}
.queryRowLabel{
    display: inline-block;
    width: 65px;
    text-align: right;
    line-height: 35px
}
.row{
    display: flex;
}
/*!important 表示权重级别高,可以覆盖其他css*/
.queryInput{
    width: 220px !important;
    margin-right: 5px
}
/* 蓝色 */
.button2 {
    background-color: #008CBA;
}
.btn-primary-blue {
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
    border-radius: 15px;
}
.btn-primary-blue.focus, .btn-primary-blue:focus {
    color: #fff;
    background-color: #0069d9;
    border-color: #0062cc;
    box-shadow: 0 0 0 .2rem rgba(38, 143, 255, .5)
}

访问:


http://localhost:8010/testList?pageNum=1

方式二、springoot+jquery+ajax+bootstrap

待补充



版权声明:本文为x18094原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。