Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 04.编辑账户

原文地址:http://www.work100.net/training/monolithic-project-iot-cloud-admin-manager-edit.html
更多教程:光束云 - 免费课程

编辑账户

序号 文内章节 视频
1 概述 -
2 后端代码实现 -
3 前端页面实现 -
4 测试验证 -
5 实例源码 -

请参照如上章节导航进行阅读

1.概述

本节实现 编辑账户 功能,实现逻辑和 新增账户 功能类似,画面效果如下:

Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 04.编辑账户

2.后端代码实现

AuthManagerMapper.xml 修改

修改 update 语句,将查询条件改为 userKey,代码如下:

<update id="update">
    UPDATE
      auth_manager
    SET
      status = #{status},
      superuser = #{superuser},
      roles = #{roles},
      updated = #{updated}
    WHERE
      user_key = #{userKey}
</update>

同时增加一个 getByUserKey 语句,代码如下:

<select id="getByUserKey" resultType="AuthManager">
    SELECT
      <include refid="authManagerColumns" />
    FROM
      auth_manager AS a
    WHERE
      a.user_key = #{userKey}
</select>

AuthManagerDao 接口修改

增加 getByUserKey 方法,代码如下:

/**
 * 获取账户对象
 *
 * @param userKey 用户Key
 * @return
 */
AuthManager getByUserKey(String userKey);

AuthManagerService 接口修改

/**
 * 更新
 *
 * @param authManager
 * @return
 */
BaseResult update(AuthManager authManager);

AuthManagerServiceImpl 实现修改

@Override
public BaseResult update(AuthManager authManager) {
    if (authManagerDao.getByUserKey(authManager.getUserKey()) == null) {
        return BaseResult.fail("用户不存在");
    }
    try {
        authManager.setUpdated(new Date());

        authManagerDao.update(authManager);
        return BaseResult.success("账户更新成功");
    } catch (Exception ex) {
        return BaseResult.fail("未知错误");
    }
}

ManagerController 修改

GET 方法

@RequestMapping(value = "edit/{userKey}", method = RequestMethod.GET)
public String edit(@PathVariable String userKey, Model model, RedirectAttributes redirectAttributes) {
    if (StringUtils.isBlank(userKey)) {
        redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("参数为空"));
        return "redirect:/auth/manager/list";
    }
    AuthManager authManager = authManagerService.getByUserKey(userKey);
    if (authManager == null) {
        redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("数据不存在"));
        return "redirect:/auth/manager/list";
    }
    model.addAttribute("authManager", authManager);
    return "auth/manager_edit";
}

POST 方法

@RequestMapping(value = "edit/{userKey}", method = RequestMethod.POST)
public String edit(@PathVariable String userKey, AuthManager authManager, Model model, RedirectAttributes redirectAttributes) {
    // 数据验证
    if (StringUtils.isBlank(userKey)) {
        redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("参数为空"));
        return "redirect:/auth/manager/list";
    }
    if (!userKey.equals(authManager.getUserKey())) {
        redirectAttributes.addFlashAttribute("baseResult", BaseResult.fail("非法请求"));
        return "redirect:/auth/manager/list";
    }
    if (StringUtils.isBlank(authManager.getRoles())) {
        model.addAttribute("baseResult", BaseResult.fail("角色不能空"));
        model.addAttribute("authManager", authManager);
        return "auth/manager_edit";
    }

    // 新增处理
    BaseResult baseResult = authManagerService.update(authManager);
    if (baseResult.getStatus() == HttpUtils.HTTP_STATUS_CODE_OK) {
        redirectAttributes.addFlashAttribute("baseResult", baseResult);
        return "redirect:/auth/manager/list";
    } else {
        model.addAttribute("baseResult", baseResult);
        return "auth/manager_edit";
    }
}

3.前端页面实现

视图文件 manager_edit.jsp

views/auth/ 目录下增加一个 manager_edit.jsp 视图文件,代码如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
    <title>编辑账户 - 后台账户 | IoT-Admin</title>
    <jsp:include page="../includes/resources_head.jsp" />
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">

    <jsp:include page="../includes/layout_header.jsp" />

    <jsp:include page="../includes/layout_left.jsp" />

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 text-dark">编辑账户</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#">后台账户</a></li>
                            <li class="breadcrumb-item active">编辑账户</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <div class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col">
                        <div class="card card-gray">
                            <!-- form start -->
                            <form:form action="/auth/manager/edit/${authManager.userKey}" id="form" method="post" modelAttribute="authManager">
                                <form:hidden path="userKey" />
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="userName">用户名</label>
                                                <form:input path="userName" cssClass="form-control" disabled="true" />
                                            </div>
                                            <div class="form-group">
                                                <label for="status">状态</label>
                                                <form:select path="status" cssClass="form-control select2" style="width: 100%;">
                                                    <option value="0" ${authManager.status==0?"selected":""}>未激活</option>
                                                    <option value="1" ${authManager.status==1?"selected":""}>激活</option>
                                                    <option value="2" ${authManager.status==2?"selected":""}>锁定</option>
                                                    <option value="3" ${authManager.status==3?"selected":""}>删除</option>
                                                </form:select>
                                            </div>
                                            <div class="form-group">
                                                <label for="created">创建时间</label>
                                                <form:input path="created" cssClass="form-control" disabled="true" />
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="roles">角色</label>
                                                <form:select path="roles" cssClass="select2" multiple="multiple" data-placeholder="请选择角色" style="width: 100%;">
                                                    <option value="admin" ${authManager.roles.contains("admin")?"selected":""}>admin</option>
                                                    <option value="editor" ${authManager.roles.contains("editor")?"selected":""}>editor</option>
                                                </form:select>
                                            </div>
                                            <div class="form-group">
                                                <label for="superuser">是否超级用户</label>
                                                <form:select path="superuser" cssClass="form-control select2" style="width: 100%;">
                                                    <option value="0" ${!authManager.superuser?"selected":""}>否</option>
                                                    <option value="1" ${authManager.superuser?"selected":""}>是</option>
                                                </form:select>
                                            </div>
                                            <div class="form-group">
                                                <label for="created">更新时间</label>
                                                <form:input path="updated" cssClass="form-control" disabled="true" />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- /.card-body -->

                                <div class="card-footer">
                                    <button type="submit" class="btn btn-primary">保存</button>
                                    <a href="/auth/manager/list" type="button" class="btn btn-default">返回列表</a>
                                </div>
                            </form:form>
                        </div>
                        <!-- /.card -->
                    </div>
                </div>
            </div>
            <!-- /.container-fluid -->
        </div>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <jsp:include page="../includes/layout_footer.jsp" />
</div>
<!-- ./wrapper -->
<jsp:include page="../includes/resources_body.jsp" />

<script>
$(function() {
    //Initialize Select2 Elements
    $('.select2').select2();

    //Initialize Select2 Elements
    $('.select2bs4').select2({
        theme: 'bootstrap4'
    });

    if (${baseResult.status != null && baseResult.status != 200}) {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top',
            showConfirmButton: false,
            timer: 2000,
            timerProgressBar: true,
            onOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer)
                toast.addEventListener('mouseleave', Swal.resumeTimer)
            }
        })

        Toast.fire({
            type: 'error',
            title: '${baseResult.message}'
        })
    }

    $("#form").validate({
        rules: {
            userName: {
                required: true,
                minlength: 4,
                maxlength: 20
            },
            password: {
                required: true,
                minlength: 6,
                maxlength: 20
            },
            roles: {
                required: true,
                minlength: 1,
                maxlength: 3
            }
        },
        messages: {
            userName: {
                required: " 请输入用户名",
                minlength: " 用户名不能小于4位",
                maxlength: " 用户名不能大于于20位"
            },
            password: {
                required: " 请输入密码",
                minlength: " 密码不能小于6位",
                maxlength: " 密码不能大于于20位"
            },
            roles: {
                required: " 请选择角色",
                minlength: " 至少选择1个角色",
                maxlength: " 至多选择3个角色"
            }
        },
        errorElement: 'span',
        errorPlacement: function(error, element) {
            error.addClass('invalid-feedback');
            element.closest('.form-group').children('label').append(error);
        },
        highlight: function(element, errorClass, validClass) {
            $(element).addClass('is-invalid');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).removeClass('is-invalid');
        }
    });
})
</script>
</body>
</html>

4.测试验证

重启 Tomcat 测试 编辑账户 功能。

5.实例源码

实例源码已经托管到如下地址:


上一篇:新增账户

下一篇:删除账户


如果对课程内容感兴趣,可以扫码关注我们的 公众号QQ群,及时关注我们的课程更新

Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 04.编辑账户
Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 04.编辑账户

上一篇:Extjs文件上传


下一篇:Win7系统删除网络驱动器盘符