专栏首页Java系列教程Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 04.编辑账户
原创

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

编辑账户

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

1.概述

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

编辑账户 - 光束云 - work100.net

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.实例源码

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

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 07.JS代码重构

    原文地址:http://www.work100.net/training/monolithic-project-iot-cloud-admin-manager-...

    光束云
  • Java单体应用 - 常用框架 - 05.综合实例(iot-admin)

    原文地址:http://www.work100.net/training/monolithic-frameworks-example.html

    光束云
  • Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 02.账户列表展示

    原文地址:http://www.work100.net/training/monolithic-project-iot-cloud-admin-manager-...

    光束云
  • angularjs 表单验证

    一、常用的表单验证指令  1. 必填项验证 某个表单输入是否已填写,只要在输入字段元素上添加HTML5标记required即可: <input type="te...

    柴小智
  • 总结一下laravel中Hash::make()遇到的坑

    ==这里遇到的坑就是laravel框架中,每次hash的值都是不一致的,跟之前写过的md5不一样,md5是唯一的,但是只要保存进去了,就算hash以后的值是不一...

    一个淡定的打工菜鸟
  • Jump Start Bootstrap 第3章

    在这一章,我们将开始使用Bootstrap的一些非常有用的HTML组件。诸如按钮、标题(headers)、导航菜单和评论系统的组件经常被用在网站上。通过组件,B...

    Remember_Ray
  • JQ实现倒计时功能

    使用JQ实现发送短信或阅读倒计时效果,结合bootstrap框架。直接上效果图:

    申霖
  • python flask 填写form

    <form role="form" method="POST"> {{ form.csrf_token }} <div class="box-body"> ...

    用户5760343
  • Angular 2 + 折腾记 :(7) 初步了解表单:模板驱动及数据驱动及脱坑要点

    表单在整个系统中的作用相当重要,这里主要扯下响应表单的实现方式。 首先需要操作表单的模块引入这两个模块; import { FormsModule, React...

    CRPER
  • Django用户登录与注册系统

    一、创建项目 1.1.创建项目和app django-admin startproject mysite_login python manage.py sta...

    zhang_derek

扫码关注云+社区

领取腾讯云代金券