Spring+SpringMVC19_Spring练习-用户管理操作3

一、用户列表展示1

 

  完成该功能的操作步骤:

  ①点击用户管理菜单发送请求到服务器端(修改用户管理菜单的url地址)

  ②创建UserController和list()方法

  ③创建UserService和list()方法

  ④创建UserDao和findAll()方法

  ⑤使用JdbcTemplate完成查询操作

  ⑥将查询数据存储到modelAndView中

  ⑦转发到user-list.jsp页面进行展示 

  代码实现:

  ①点击用户管理菜单发送请求到服务器端(修改用户管理菜单的url地址)

    aside.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<aside class="main-sidebar">
    <!-- sidebar: style can be found in sidebar.less -->
    <section class="sidebar">
        <!-- Sidebar user panel -->
        <div class="user-panel">
            <div class="pull-left image">
                <img src="${pageContext.request.contextPath}/img/user2-160x160.jpg"
                    class="img-circle" alt="User Image">
            </div>
            <div class="pull-left info">
                <p>
                    <security:authentication property="principal.username" />
                </p>
                <a href="#"><i class="fa fa-circle text-success"></i> 在线</a>
            </div>
        </div>

        <!-- sidebar menu: : style can be found in sidebar.less -->
        <ul class="sidebar-menu">
            <li class="header">菜单</li>
            <li id="admin-index"><a
                href="${pageContext.request.contextPath}/pages/main.jsp"><i
                    class="fa fa-dashboard"></i> <span>首页</span></a></li>

            <li class="treeview"><a href="#"> <i class="fa fa-cogs"></i>
                    <span>系统管理</span> <span class="pull-right-container"> <i
                        class="fa fa-angle-left pull-right"></i>
                </span>


            </a>
                <ul class="treeview-menu">

                    <li><a
                        <%--href="${pageContext.request.contextPath}/pages/user-list.jsp"> <i--%>
                            href="${pageContext.request.contextPath}/user/list"> <i
                            class="fa fa-circle-o"></i> 用户管理
                    </a></li>
                    <li><a
                        <%--href="${pageContext.request.contextPath}/pages/role-list.jsp"> <i--%>
                            href="${pageContext.request.contextPath}/role/list"> <i
                            class="fa fa-circle-o"></i> 角色管理
                    </a></li>
                    <li><a
                        href="${pageContext.request.contextPath}/pages/syslog-list.jsp"> <i
                            class="fa fa-circle-o"></i> 访问日志
                    </a></li>
                </ul></li>
            <li class="treeview"><a href="#"> <i class="fa fa-cube"></i>
                    <span>基础数据</span> <span class="pull-right-container"> <i
                        class="fa fa-angle-left pull-right"></i>
                </span>
            </a>
                <ul class="treeview-menu">

                    <li><a
                        href="#">
                            <i class="fa fa-circle-o"></i> 产品管理
                    </a></li>
                    <li><a
                        href="#">
                            <i class="fa fa-circle-o"></i> 订单管理
                    </a></li>

                </ul></li>

        </ul>
    </section>
    <!-- /.sidebar -->
</aside>

  ②User增加角色属性

package com.itheima.domain;

import java.util.List;

public class User {

    private Long id;
    private String username;
    private String email;
    private String password;
    private String phoneNum;

    //当前用户具备哪些角色
    private List<Role> roles;

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhoneNum() {
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", email='" + email + '\'' +
                ", password='" + password + '\'' +
                ", phoneNum='" + phoneNum + '\'' +
                '}';
    }
}

  ③创建UserController和list()方法

package com.itheima.controlloer;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> userList = userService.list();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }
}

  ④创建UserService和list()方法

package com.itheima.service;

import com.itheima.domain.User;
import java.util.List;

public interface UserService {

    public List<User> list();
}
package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {

    private UserDao userDao;
    private RoleDao roleDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {

        List<User> userList = userDao.findAll();
        //封装userList中的每一个User的roles数据
        for (User user : userList) {
            //获得user的id
            Long id = user.getId();
            //将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roles= roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }
}

  ⑤创建UserDao和findAll()方法

package com.itheima.dao;

import com.itheima.domain.User;
import java.util.List;

public interface UserDao {

    List<User> findAll();
}
package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> findAll() {

        List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }


}

  ⑥配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="roleDao" class="com.itheima.dao.impl.RoleDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="roleService" class="com.itheima.service.impl.RoleServiceImpl">
        <property name="roleDao" ref="roleDao"/>
    </bean>

    <bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
        <property name="userDao" ref="userDao"/>
        <property name="roleDao" ref="roleDao"/>
    </bean>
</beans>

  ⑦页面展示user-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>数据 - AdminLTE2定制版</title>
<meta name="description" content="AdminLTE2定制版">
<meta name="keywords" content="AdminLTE2定制版">

<!-- Tell the browser to be responsive to screen width -->
<meta
    content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"
    name="viewport">

<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionicons/css/ionicons.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/iCheck/square/blue.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/morris/morris.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datepicker/datepicker3.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datatables/dataTables.bootstrap.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.theme.default.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/select2/select2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/colorpicker/bootstrap-colorpicker.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-markdown/css/bootstrap-markdown.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/AdminLTE.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/skins/_all-skins.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/css/style.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.skinNice.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-slider/slider.css">
</head>

<body class="hold-transition skin-blue sidebar-mini">

    <div class="wrapper">

        <!-- 页面头部 -->
        <jsp:include page="header.jsp"></jsp:include>
        <!-- 页面头部 /-->

        <!-- 导航侧栏 -->
        <jsp:include page="aside.jsp"></jsp:include>
        <!-- 导航侧栏 /-->

        <!-- 内容区域 -->
        <div class="content-wrapper">

            <!-- 内容头部 -->
            <section class="content-header">
            <h1>
                用户管理 <small>全部用户</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="${pageContext.request.contextPath}/index.jsp"><i
                        class="fa fa-dashboard"></i> 首页</a></li>
                <li><a
                    href="${pageContext.request.contextPath}/user/findAll.do">用户管理</a></li>

                <li class="active">全部用户</li>
            </ol>
            </section>
            <!-- 内容头部 /-->

                <!-- 正文区域 -->
                <section class="content"> <!-- .box-body -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">列表</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-default" title="新建" onclick="location.href='${pageContext.request.contextPath}/pages/user-add.jsp'">
                                            <i class="fa fa-file-o"></i> 新建
                                        </button>
                                        
                                        <button type="button" class="btn btn-default" title="刷新">
                                            <i class="fa fa-refresh"></i> 刷新
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="box-tools pull-right">
                                <div class="has-feedback">
                                    <input type="text" class="form-control input-sm"
                                        placeholder="搜索"> <span
                                        class="glyphicon glyphicon-search form-control-feedback"></span>
                                </div>
                            </div>
                            <!--工具栏/-->

                            <!--数据列表-->
                            <table id="dataList"
                                class="table table-bordered table-striped table-hover dataTable">
                                <thead>
                                    <tr>
                                        <th class="" style="padding-right: 0px"><input
                                            id="selall" type="checkbox" class="icheckbox_square-blue">
                                        </th>
                                        <th class="sorting_asc">ID</th>
                                        <th class="sorting_desc">用户名</th>
                                        <th class="sorting_asc sorting_asc_disabled">邮箱</th>
                                        <th class="sorting_desc sorting_desc_disabled">联系电话</th>
                                        <th class="sorting">具有角色</th>
                                        <th class="sorting">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                  <c:forEach items="${userList}" var="user">
                                        <tr>
                                            <td><input name="ids" type="checkbox"></td>
                                            <td>${user.id}</td>
                                            <td>${user.username}</td>
                                            <td>${user.email}</td>
                                            <td>${user.phoneNum}</td>
                                            <td class="text-center">
                                                <c:forEach items="${user.roles}" var="role">
                                                    &nbsp;${role.roleName}
                                                </c:forEach>
                                                <%--课程研究员&nbsp;讲师&nbsp;--%>
                                            </td>
                                            <td class="text-center">
                                                <a href="javascript:void(0);" class="btn bg-olive btn-xs">删除</a>
                                            </td>
                                        </tr>
                                  </c:forEach>

                                        <%--<tr>--%>
                                            <%--<td><input name="ids" type="checkbox"></td>--%>
                                            <%--<td>2</td>--%>
                                            <%--<td>李四</td>--%>
                                            <%--<td>lisi@itcast.cn</td>--%>
                                            <%--<td>13999999999</td>--%>
                                            <%--<td class="text-center">--%>
                                                <%--讲师&nbsp;--%>
                                            <%--</td>--%>
                                        <%--</tr>--%>

                                </tbody>

                            </table>
                            <!--数据列表/-->

                        </div>
                        <!-- 数据表格 /-->

                    </div>
                    <!-- /.box-body -->



                </div>

                </section>
                <!-- 正文区域 /-->

            </div>
            <!-- @@close -->
            <!-- 内容区域 /-->

            <!-- 底部导航 -->
            <footer class="main-footer">
            <div class="pull-right hidden-xs">
                <b>Version</b> 1.0.8
            </div>
            <strong>Copyright &copy; 2018-2020 <a
                href="http://www.itcast.cn">研究院研发部</a>.
            </strong> All rights reserved. </footer>
            <!-- 底部导航 /-->

        </div>

        <script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
        <script src="../plugins/jQueryUI/jquery-ui.min.js"></script>
        <script>
            $.widget.bridge('uibutton', $.ui.button);
        </script>
        <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
        <script src="../plugins/raphael/raphael-min.js"></script>
        <script src="../plugins/morris/morris.min.js"></script>
        <script src="../plugins/sparkline/jquery.sparkline.min.js"></script>
        <script src="../plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
        <script src="../plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
        <script src="../plugins/knob/jquery.knob.js"></script>
        <script src="../plugins/daterangepicker/moment.min.js"></script>
        <script src="../plugins/daterangepicker/daterangepicker.js"></script>
        <script src="../plugins/daterangepicker/daterangepicker.zh-CN.js"></script>
        <script src="../plugins/datepicker/bootstrap-datepicker.js"></script>
        <script
            src="../plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
        <script
            src="../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
        <script src="../plugins/slimScroll/jquery.slimscroll.min.js"></script>
        <script src="../plugins/fastclick/fastclick.js"></script>
        <script src="../plugins/iCheck/icheck.min.js"></script>
        <script src="../plugins/adminLTE/js/app.min.js"></script>
        <script src="../plugins/treeTable/jquery.treetable.js"></script>
        <script src="../plugins/select2/select2.full.min.js"></script>
        <script src="../plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
        <script
            src="../plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.zh-CN.js"></script>
        <script src="../plugins/bootstrap-markdown/js/bootstrap-markdown.js"></script>
        <script
            src="../plugins/bootstrap-markdown/locale/bootstrap-markdown.zh.js"></script>
        <script src="../plugins/bootstrap-markdown/js/markdown.js"></script>
        <script src="../plugins/bootstrap-markdown/js/to-markdown.js"></script>
        <script src="../plugins/ckeditor/ckeditor.js"></script>
        <script src="../plugins/input-mask/jquery.inputmask.js"></script>
        <script
            src="../plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
        <script src="../plugins/input-mask/jquery.inputmask.extensions.js"></script>
        <script src="../plugins/datatables/jquery.dataTables.min.js"></script>
        <script src="../plugins/datatables/dataTables.bootstrap.min.js"></script>
        <script src="../plugins/chartjs/Chart.min.js"></script>
        <script src="../plugins/flot/jquery.flot.min.js"></script>
        <script src="../plugins/flot/jquery.flot.resize.min.js"></script>
        <script src="../plugins/flot/jquery.flot.pie.min.js"></script>
        <script src="../plugins/flot/jquery.flot.categories.min.js"></script>
        <script src="../plugins/ionslider/ion.rangeSlider.min.js"></script>
        <script src="../plugins/bootstrap-slider/bootstrap-slider.js"></script>
        <script>
            $(document).ready(function() {
                // 选择框
                $(".select2").select2();

                // WYSIHTML5编辑器
                $(".textarea").wysihtml5({
                    locale : 'zh-CN'
                });
            });

            // 设置激活菜单
            function setSidebarActive(tagUri) {
                var liObj = $("#" + tagUri);
                if (liObj.length > 0) {
                    liObj.parent().parent().addClass("active");
                    liObj.addClass("active");
                }
            }

            $(document)
                    .ready(
                            function() {

                                // 激活导航位置
                                setSidebarActive("admin-datalist");

                                // 列表按钮 
                                $("#dataList td input[type='checkbox']")
                                        .iCheck(
                                                {
                                                    checkboxClass : 'icheckbox_square-blue',
                                                    increaseArea : '20%'
                                                });
                                // 全选操作 
                                $("#selall")
                                        .click(
                                                function() {
                                                    var clicks = $(this).is(
                                                            ':checked');
                                                    if (!clicks) {
                                                        $(
                                                                "#dataList td input[type='checkbox']")
                                                                .iCheck(
                                                                        "uncheck");
                                                    } else {
                                                        $(
                                                                "#dataList td input[type='checkbox']")
                                                                .iCheck("check");
                                                    }
                                                    $(this).data("clicks",
                                                            !clicks);
                                                });
                            });
        </script>
</body>

</html>

 启动tomcat服务器,成功访问用户管理:

  

二、用户添加操作-添加页面展示

 需求:添加用户,需求图如下:

  

   新建用户时,点击新建按钮先去到添加用户的页面user-add.jsp,在添加用户页面需要展示可供选择的角色信息,因此来到添加页面时需要查询所有的角色信息并展示 

  代码实现:

  user-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>数据 - AdminLTE2定制版</title>
<meta name="description" content="AdminLTE2定制版">
<meta name="keywords" content="AdminLTE2定制版">

<!-- Tell the browser to be responsive to screen width -->
<meta
    content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"
    name="viewport">

<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionicons/css/ionicons.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/iCheck/square/blue.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/morris/morris.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datepicker/datepicker3.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datatables/dataTables.bootstrap.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.theme.default.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/select2/select2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/colorpicker/bootstrap-colorpicker.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-markdown/css/bootstrap-markdown.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/AdminLTE.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/skins/_all-skins.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/css/style.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.skinNice.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-slider/slider.css">
</head>

<body class="hold-transition skin-blue sidebar-mini">

    <div class="wrapper">

        <!-- 页面头部 -->
        <jsp:include page="header.jsp"></jsp:include>
        <!-- 页面头部 /-->

        <!-- 导航侧栏 -->
        <jsp:include page="aside.jsp"></jsp:include>
        <!-- 导航侧栏 /-->

        <!-- 内容区域 -->
        <div class="content-wrapper">

            <!-- 内容头部 -->
            <section class="content-header">
            <h1>
                用户管理 <small>全部用户</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="${pageContext.request.contextPath}/index.jsp"><i
                        class="fa fa-dashboard"></i> 首页</a></li>
                <li><a
                    href="${pageContext.request.contextPath}/user/findAll.do">用户管理</a></li>

                <li class="active">全部用户</li>
            </ol>
            </section>
            <!-- 内容头部 /-->

                <!-- 正文区域 -->
                <section class="content"> <!-- .box-body -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">列表</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <%--<button type="button" class="btn btn-default" title="新建" onclick="location.href='${pageContext.request.contextPath}/pages/user-add.jsp'">--%>
                                            <button type="button" class="btn btn-default" title="新建" onclick="location.href='${pageContext.request.contextPath}/user/saveUI'">
                                            <i class="fa fa-file-o"></i> 新建
                                        </button>
                                        
                                        <button type="button" class="btn btn-default" title="刷新">
                                            <i class="fa fa-refresh"></i> 刷新
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="box-tools pull-right">
                                <div class="has-feedback">
                                    <input type="text" class="form-control input-sm"
                                        placeholder="搜索"> <span
                                        class="glyphicon glyphicon-search form-control-feedback"></span>
                                </div>
                            </div>
                            <!--工具栏/-->

                            <!--数据列表-->
                            <table id="dataList"
                                class="table table-bordered table-striped table-hover dataTable">
                                <thead>
                                    <tr>
                                        <th class="" style="padding-right: 0px"><input
                                            id="selall" type="checkbox" class="icheckbox_square-blue">
                                        </th>
                                        <th class="sorting_asc">ID</th>
                                        <th class="sorting_desc">用户名</th>
                                        <th class="sorting_asc sorting_asc_disabled">邮箱</th>
                                        <th class="sorting_desc sorting_desc_disabled">联系电话</th>
                                        <th class="sorting">具有角色</th>
                                        <th class="sorting">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach items="${userList}" var="user">
                                        <tr>
                                            <td><input name="ids" type="checkbox"></td>
                                            <td>${user.id}</td>
                                            <td>${user.username}</td>
                                            <td>${user.email}</td>
                                            <td>${user.phoneNum}</td>
                                            <td class="text-center">
                                                <c:forEach items="${user.roles}" var="role">
                                                    &nbsp;${role.roleName}
                                                </c:forEach>
                                                <%--课程研究员&nbsp;讲师&nbsp;--%>
                                            </td>
                                            <td class="text-center">
                                                <a href="javascript:void(0);" class="btn bg-olive btn-xs">删除</a>
                                            </td>
                                        </tr>
                                    </c:forEach>

                                        <%--<tr>--%>
                                            <%--<td><input name="ids" type="checkbox"></td>--%>
                                            <%--<td>2</td>--%>
                                            <%--<td>李四</td>--%>
                                            <%--<td>lisi@itcast.cn</td>--%>
                                            <%--<td>13999999999</td>--%>
                                            <%--<td class="text-center">--%>
                                                <%--讲师&nbsp;--%>
                                            <%--</td>--%>
                                        <%--</tr>--%>

                                </tbody>

                            </table>
                            <!--数据列表/-->

                        </div>
                        <!-- 数据表格 /-->

                    </div>
                    <!-- /.box-body -->



                </div>

                </section>
                <!-- 正文区域 /-->

            </div>
            <!-- @@close -->
            <!-- 内容区域 /-->

            <!-- 底部导航 -->
            <footer class="main-footer">
            <div class="pull-right hidden-xs">
                <b>Version</b> 1.0.8
            </div>
            <strong>Copyright &copy; 2018-2020 <a
                href="http://www.itcast.cn">研究院研发部</a>.
            </strong> All rights reserved. </footer>
            <!-- 底部导航 /-->

        </div>

        <script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
        <script src="../plugins/jQueryUI/jquery-ui.min.js"></script>
        <script>
            $.widget.bridge('uibutton', $.ui.button);
        </script>
        <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
        <script src="../plugins/raphael/raphael-min.js"></script>
        <script src="../plugins/morris/morris.min.js"></script>
        <script src="../plugins/sparkline/jquery.sparkline.min.js"></script>
        <script src="../plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
        <script src="../plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
        <script src="../plugins/knob/jquery.knob.js"></script>
        <script src="../plugins/daterangepicker/moment.min.js"></script>
        <script src="../plugins/daterangepicker/daterangepicker.js"></script>
        <script src="../plugins/daterangepicker/daterangepicker.zh-CN.js"></script>
        <script src="../plugins/datepicker/bootstrap-datepicker.js"></script>
        <script
            src="../plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
        <script
            src="../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
        <script src="../plugins/slimScroll/jquery.slimscroll.min.js"></script>
        <script src="../plugins/fastclick/fastclick.js"></script>
        <script src="../plugins/iCheck/icheck.min.js"></script>
        <script src="../plugins/adminLTE/js/app.min.js"></script>
        <script src="../plugins/treeTable/jquery.treetable.js"></script>
        <script src="../plugins/select2/select2.full.min.js"></script>
        <script src="../plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
        <script
            src="../plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.zh-CN.js"></script>
        <script src="../plugins/bootstrap-markdown/js/bootstrap-markdown.js"></script>
        <script
            src="../plugins/bootstrap-markdown/locale/bootstrap-markdown.zh.js"></script>
        <script src="../plugins/bootstrap-markdown/js/markdown.js"></script>
        <script src="../plugins/bootstrap-markdown/js/to-markdown.js"></script>
        <script src="../plugins/ckeditor/ckeditor.js"></script>
        <script src="../plugins/input-mask/jquery.inputmask.js"></script>
        <script
            src="../plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
        <script src="../plugins/input-mask/jquery.inputmask.extensions.js"></script>
        <script src="../plugins/datatables/jquery.dataTables.min.js"></script>
        <script src="../plugins/datatables/dataTables.bootstrap.min.js"></script>
        <script src="../plugins/chartjs/Chart.min.js"></script>
        <script src="../plugins/flot/jquery.flot.min.js"></script>
        <script src="../plugins/flot/jquery.flot.resize.min.js"></script>
        <script src="../plugins/flot/jquery.flot.pie.min.js"></script>
        <script src="../plugins/flot/jquery.flot.categories.min.js"></script>
        <script src="../plugins/ionslider/ion.rangeSlider.min.js"></script>
        <script src="../plugins/bootstrap-slider/bootstrap-slider.js"></script>
        <script>
            $(document).ready(function() {
                // 选择框
                $(".select2").select2();

                // WYSIHTML5编辑器
                $(".textarea").wysihtml5({
                    locale : 'zh-CN'
                });
            });

            // 设置激活菜单
            function setSidebarActive(tagUri) {
                var liObj = $("#" + tagUri);
                if (liObj.length > 0) {
                    liObj.parent().parent().addClass("active");
                    liObj.addClass("active");
                }
            }

            $(document)
                    .ready(
                            function() {

                                // 激活导航位置
                                setSidebarActive("admin-datalist");

                                // 列表按钮 
                                $("#dataList td input[type='checkbox']")
                                        .iCheck(
                                                {
                                                    checkboxClass : 'icheckbox_square-blue',
                                                    increaseArea : '20%'
                                                });
                                // 全选操作 
                                $("#selall")
                                        .click(
                                                function() {
                                                    var clicks = $(this).is(
                                                            ':checked');
                                                    if (!clicks) {
                                                        $(
                                                                "#dataList td input[type='checkbox']")
                                                                .iCheck(
                                                                        "uncheck");
                                                    } else {
                                                        $(
                                                                "#dataList td input[type='checkbox']")
                                                                .iCheck("check");
                                                    }
                                                    $(this).data("clicks",
                                                            !clicks);
                                                });
                            });
        </script>
</body>

</html>
package com.itheima.controlloer;

import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> userList = userService.list();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/saveUI")
    public ModelAndView saveUI(){
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList",roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }
}

  user-add.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>数据 - AdminLTE2定制版</title>
<meta name="description" content="AdminLTE2定制版">
<meta name="keywords" content="AdminLTE2定制版">

<!-- Tell the browser to be responsive to screen width -->
<meta
    content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"
    name="viewport">


<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionicons/css/ionicons.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/iCheck/square/blue.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/morris/morris.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datepicker/datepicker3.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datatables/dataTables.bootstrap.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.theme.default.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/select2/select2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/colorpicker/bootstrap-colorpicker.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-markdown/css/bootstrap-markdown.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/AdminLTE.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/skins/_all-skins.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/css/style.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.skinNice.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-slider/slider.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.css">
</head>

<body class="hold-transition skin-purple sidebar-mini">

    <div class="wrapper">

        <!-- 页面头部 -->
        <jsp:include page="header.jsp"></jsp:include>
        <!-- 页面头部 /-->
        <!-- 导航侧栏 -->
        <jsp:include page="aside.jsp"></jsp:include>
        <!-- 导航侧栏 /-->

        <!-- 内容区域 -->
        <div class="content-wrapper">

            <!-- 内容头部 -->
            <section class="content-header">
            <h1>
                用户管理 <small>用户表单</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="${pageContext.request.contextPath}/index.jsp"><i
                        class="fa fa-dashboard"></i> 首页</a></li>
                <li><a
                    href="${pageContext.request.contextPath}/user/findAll.do">用户管理</a></li>
                <li class="active">用户表单</li>
            </ol>
            </section>
            <!-- 内容头部 /-->

            <form action="${pageContext.request.contextPath}/user/save"
                method="post">
                <!-- 正文区域 -->
                <section class="content"> <!--产品信息-->

                <div class="panel panel-default">
                    <div class="panel-heading">用户信息</div>
                    <div class="row data-type">

                        <div class="col-md-2 title">用户名称</div>
                        <div class="col-md-4 data">
                            <input type="text" class="form-control" name="username"
                                placeholder="用户名称" value="">
                        </div>
                        <div class="col-md-2 title">密码</div>
                        <div class="col-md-4 data">
                            <input type="password" class="form-control" name="password"
                                placeholder="密码" value="">
                        </div>
                        <div class="col-md-2 title">邮箱</div>
                        <div class="col-md-4 data">
                            <input type="text" class="form-control" name="email"
                                placeholder="邮箱" value="">
                        </div>
                        <div class="col-md-2 title">联系电话</div>
                        <div class="col-md-4 data">
                            <input type="text" class="form-control" name="phoneNum"
                                placeholder="联系电话" value="">
                        </div>
                        <div class="col-md-2 title">用户角色</div>
                        <div class="col-md-10 data">
                            <c:forEach items="${roleList}" var="role">
                                <input class="" type="checkbox" name="roleIds" value="${role.id}">${role.roleName}
                            </c:forEach>
                            <%--<input class="" type="checkbox" name="roleId" value="1">院长--%>
                            <%--<input type="checkbox" name="roleId" value="2">课程研究员--%>
                            <%--<input type="checkbox" name="roleId" value="3">讲师--%>
                            <%--<input type="checkbox" name="roleId" value="4">助教--%>
                            <%--<input type="checkbox" name="roleId" value="5">就业指导--%>
                            <%--<input type="checkbox" name="roleId" value="6">班主任--%>
                        </div>

                    </div>
                </div>
                <!--订单信息/--> <!--工具栏-->
                <div class="box-tools text-center">
                    <button type="submit" class="btn bg-maroon">保存</button>
                    <button type="button" class="btn bg-default"
                        onclick="history.back(-1);">返回</button>
                </div>
                <!--工具栏/--> </section>
                <!-- 正文区域 /-->
            </form>
        </div>
        <!-- 内容区域 /-->

        <!-- 底部导航 -->
        <footer class="main-footer">
        <div class="pull-right hidden-xs">
            <b>Version</b> 1.0.8
        </div>
        <strong>Copyright &copy; 2014-2017 <a
            href="http://www.itcast.cn">研究院研发部</a>.
        </strong> All rights reserved. </footer>
        <!-- 底部导航 /-->

    </div>


    <script
        src="${pageContext.request.contextPath}/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/jQueryUI/jquery-ui.min.js"></script>
    <script>
        $.widget.bridge('uibutton', $.ui.button);
    </script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap/js/bootstrap.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/raphael/raphael-min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/morris/morris.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/sparkline/jquery.sparkline.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/knob/jquery.knob.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/daterangepicker/moment.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.zh-CN.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/datepicker/bootstrap-datepicker.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/slimScroll/jquery.slimscroll.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/fastclick/fastclick.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/iCheck/icheck.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/adminLTE/js/app.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/select2/select2.full.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.zh-CN.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/js/bootstrap-markdown.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/locale/bootstrap-markdown.zh.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/js/markdown.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-markdown/js/to-markdown.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/ckeditor/ckeditor.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/input-mask/jquery.inputmask.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/input-mask/jquery.inputmask.extensions.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/datatables/jquery.dataTables.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/datatables/dataTables.bootstrap.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/chartjs/Chart.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.resize.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.pie.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/flot/jquery.flot.categories.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.min.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-slider/bootstrap-slider.js"></script>
    <script
        src="${pageContext.request.contextPath}/plugins/bootstrap-datetimepicker/bootstrap-datetimepicker.min.js"></script>

    <script>
        $(document).ready(function() {
            // 选择框
            $(".select2").select2();

            // WYSIHTML5编辑器
            $(".textarea").wysihtml5({
                locale : 'zh-CN'
            });
        });

        // 设置激活菜单
        function setSidebarActive(tagUri) {
            var liObj = $("#" + tagUri);
            if (liObj.length > 0) {
                liObj.parent().parent().addClass("active");
                liObj.addClass("active");
            }
        }
    </script>


</body>

</html>

  启动tomcat服务器,进入用户管理,点击新建

  

三、用户添加操作-添加数据到数据库

 添加用户页面有两部分数据,一部分属于用户基础数据需要插入到用户表user中,另一部分是用户的角色数据,需要插入到中间表sys_user_role中。

 点击保存,查看提交数据:

  

package com.itheima.controlloer;

import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> userList = userService.list();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/saveUI")
    public ModelAndView saveUI(){
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList",roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(User user,Long[] roleIds){
        userService.save(user,roleIds);
        return "redirect:/user/list";
    }
}
package com.itheima.service;

import com.itheima.domain.User;
import java.util.List;

public interface UserService {

    public List<User> list();
    void save(User user, Long[] roleIds);
}
package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import java.util.List;

public class UserServiceImpl implements UserService {

    private UserDao userDao;
    private RoleDao roleDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {

        List<User> userList = userDao.findAll();
        //封装userList中的每一个User的roles数据
        for (User user : userList) {
            //获得user的id
            Long id = user.getId();
            //将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roles= roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }

    public void save(User user, Long[] roleIds) {
        //第一步:向sys_user表中存储数据
        Long userId = userDao.save(user);
        //第二步:向sys_user_role关系表中存储多条数据
        userDao.saveUserRoleRel(userId,roleIds);
    }
}
package com.itheima.dao;

import com.itheima.domain.User;
import java.util.List;

public interface UserDao {

    List<User> findAll();
    Long save(User user);
    void saveUserRoleRel(Long userId, Long[] roleIds);
}
package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> findAll() {

        List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    public Long save(User user) {
        int ifsuccess = jdbcTemplate.update("insert into sys_user values(?,?,?,?,?)", null, user.getUsername(), user.getPassword(), user.getEmail(), user.getPhoneNum());
        return 0L;//返回当前保存用户的id 该id是数据库自动生成的
    }

    public void saveUserRoleRel(Long userId, Long[] roleIds) {

        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values(?,?)",userId,roleId);
        }
    }
}

  这里留下了一个问题,在dao层操作后如何获得自增的主键id值呢? 

四、用户添加操作-添加数据到数据库2

 添加用户时用户分配的角色信息应存储到中间表sys_user_role表中,需要用户的id,角色的id,而角色的id由 前台页面点选的,用户的id应该是在保存操作由mysql主键自动生成的,那如何获取mysql自增的主键值呢?

 使用JdbcTemplate执行插入操作时获取mysql自增的主键值:

 添加操作的dao层代码如下:  

package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> findAll() {

        List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    public Long save(final User user) {
        //创建PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                //使用原始jdbc完成有个PreparedStatement的组建
                PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setString(2,user.getUsername());
                preparedStatement.setString(3,user.getEmail());
                preparedStatement.setString(4,user.getPassword());
                preparedStatement.setString(5,user.getPhoneNum());
                return preparedStatement;
            }
        };
        //创建keyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator,keyHolder);
        //获得生成的主键
        long userId = keyHolder.getKey().longValue();
        return userId;

//        int ifsuccess = jdbcTemplate.update("insert into sys_user values(?,?,?,?,?)", null, user.getUsername(), user.getPassword(), user.getEmail(), user.getPhoneNum());
//        return 0L;//返回当前保存用户的id 该id是数据库自动生成的
    }

    public void saveUserRoleRel(Long userId, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values(?,?)",userId,roleId);
        }
    }
}

  新建用户信息

  

  

五、删除用户操作

 删除用户功能的需求如图所示:
 

 操作步骤如下:

  ①点击用户列表的删除按钮,发送请求到服务器端

  ②编写UserController的del()方法

  ③编写UserService的del()方法

  ④编写UserDao的delUserRoleRel()方法

  ⑤跳回当前用户列表页面

  完成用户的删除操作,不仅要删除用户表数据,同时需要将用户和角色的关联表数据进行删除: 

 代码实现:

  user-list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- 页面meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>数据 - AdminLTE2定制版</title>
<meta name="description" content="AdminLTE2定制版">
<meta name="keywords" content="AdminLTE2定制版">

<!-- Tell the browser to be responsive to screen width -->
<meta
    content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"
    name="viewport">

<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionicons/css/ionicons.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/iCheck/square/blue.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/morris/morris.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datepicker/datepicker3.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/datatables/dataTables.bootstrap.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/treeTable/jquery.treetable.theme.default.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/select2/select2.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/colorpicker/bootstrap-colorpicker.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-markdown/css/bootstrap-markdown.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/AdminLTE.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/adminLTE/css/skins/_all-skins.min.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/css/style.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/ionslider/ion.rangeSlider.skinNice.css">
<link rel="stylesheet"
    href="${pageContext.request.contextPath}/plugins/bootstrap-slider/slider.css">

    <script>
        function delUser(userId) {
            if(confirm("您确认要删除吗?")){
                location.href="${pageContext.request.contextPath}/user/del/"+userId;
            }
        }
    </script>

</head>

<body class="hold-transition skin-blue sidebar-mini">

    <div class="wrapper">

        <!-- 页面头部 -->
        <jsp:include page="header.jsp"></jsp:include>
        <!-- 页面头部 /-->

        <!-- 导航侧栏 -->
        <jsp:include page="aside.jsp"></jsp:include>
        <!-- 导航侧栏 /-->

        <!-- 内容区域 -->
        <div class="content-wrapper">

            <!-- 内容头部 -->
            <section class="content-header">
            <h1>
                用户管理 <small>全部用户</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="${pageContext.request.contextPath}/index.jsp"><i
                        class="fa fa-dashboard"></i> 首页</a></li>
                <li><a
                    href="${pageContext.request.contextPath}/user/findAll.do">用户管理</a></li>

                <li class="active">全部用户</li>
            </ol>
            </section>
            <!-- 内容头部 /-->

                <!-- 正文区域 -->
                <section class="content"> <!-- .box-body -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title">列表</h3>
                    </div>

                    <div class="box-body">

                        <!-- 数据表格 -->
                        <div class="table-box">

                            <!--工具栏-->
                            <div class="pull-left">
                                <div class="form-group form-inline">
                                    <div class="btn-group">
                                        <%--<button type="button" class="btn btn-default" title="新建" onclick="location.href='${pageContext.request.contextPath}/pages/user-add.jsp'">--%>
                                            <button type="button" class="btn btn-default" title="新建" onclick="location.href='${pageContext.request.contextPath}/user/saveUI'">
                                            <i class="fa fa-file-o"></i> 新建
                                        </button>
                                        
                                        <button type="button" class="btn btn-default" title="刷新">
                                            <i class="fa fa-refresh"></i> 刷新
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="box-tools pull-right">
                                <div class="has-feedback">
                                    <input type="text" class="form-control input-sm"
                                        placeholder="搜索"> <span
                                        class="glyphicon glyphicon-search form-control-feedback"></span>
                                </div>
                            </div>
                            <!--工具栏/-->

                            <!--数据列表-->
                            <table id="dataList"
                                class="table table-bordered table-striped table-hover dataTable">
                                <thead>
                                    <tr>
                                        <th class="" style="padding-right: 0px"><input
                                            id="selall" type="checkbox" class="icheckbox_square-blue">
                                        </th>
                                        <th class="sorting_asc">ID</th>
                                        <th class="sorting_desc">用户名</th>
                                        <th class="sorting_asc sorting_asc_disabled">邮箱</th>
                                        <th class="sorting_desc sorting_desc_disabled">联系电话</th>
                                        <th class="sorting">具有角色</th>
                                        <th class="sorting">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach items="${userList}" var="user">
                                        <tr>
                                            <td><input name="ids" type="checkbox"></td>
                                            <td>${user.id}</td>
                                            <td>${user.username}</td>
                                            <td>${user.email}</td>
                                            <td>${user.phoneNum}</td>
                                            <td class="text-center">
                                                <c:forEach items="${user.roles}" var="role">
                                                    &nbsp;${role.roleName}
                                                </c:forEach>
                                                <%--课程研究员&nbsp;讲师&nbsp;--%>
                                            </td>
                                            <td class="text-center">
                                                <a href="javascript:void(0);" onclick="delUser('${user.id}')" class="btn bg-olive btn-xs">删除</a>
                                            </td>
                                        </tr>
                                    </c:forEach>

                                        <%--<tr>--%>
                                            <%--<td><input name="ids" type="checkbox"></td>--%>
                                            <%--<td>2</td>--%>
                                            <%--<td>李四</td>--%>
                                            <%--<td>lisi@itcast.cn</td>--%>
                                            <%--<td>13999999999</td>--%>
                                            <%--<td class="text-center">--%>
                                                <%--讲师&nbsp;--%>
                                            <%--</td>--%>
                                        <%--</tr>--%>

                                </tbody>

                            </table>
                            <!--数据列表/-->

                        </div>
                        <!-- 数据表格 /-->

                    </div>
                    <!-- /.box-body -->



                </div>

                </section>
                <!-- 正文区域 /-->

            </div>
            <!-- @@close -->
            <!-- 内容区域 /-->

            <!-- 底部导航 -->
            <footer class="main-footer">
            <div class="pull-right hidden-xs">
                <b>Version</b> 1.0.8
            </div>
            <strong>Copyright &copy; 2018-2020 <a
                href="http://www.itcast.cn">研究院研发部</a>.
            </strong> All rights reserved. </footer>
            <!-- 底部导航 /-->

        </div>

        <script src="../plugins/jQuery/jquery-2.2.3.min.js"></script>
        <script src="../plugins/jQueryUI/jquery-ui.min.js"></script>
        <script>
            $.widget.bridge('uibutton', $.ui.button);
        </script>
        <script src="../plugins/bootstrap/js/bootstrap.min.js"></script>
        <script src="../plugins/raphael/raphael-min.js"></script>
        <script src="../plugins/morris/morris.min.js"></script>
        <script src="../plugins/sparkline/jquery.sparkline.min.js"></script>
        <script src="../plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
        <script src="../plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
        <script src="../plugins/knob/jquery.knob.js"></script>
        <script src="../plugins/daterangepicker/moment.min.js"></script>
        <script src="../plugins/daterangepicker/daterangepicker.js"></script>
        <script src="../plugins/daterangepicker/daterangepicker.zh-CN.js"></script>
        <script src="../plugins/datepicker/bootstrap-datepicker.js"></script>
        <script
            src="../plugins/datepicker/locales/bootstrap-datepicker.zh-CN.js"></script>
        <script
            src="../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
        <script src="../plugins/slimScroll/jquery.slimscroll.min.js"></script>
        <script src="../plugins/fastclick/fastclick.js"></script>
        <script src="../plugins/iCheck/icheck.min.js"></script>
        <script src="../plugins/adminLTE/js/app.min.js"></script>
        <script src="../plugins/treeTable/jquery.treetable.js"></script>
        <script src="../plugins/select2/select2.full.min.js"></script>
        <script src="../plugins/colorpicker/bootstrap-colorpicker.min.js"></script>
        <script
            src="../plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.zh-CN.js"></script>
        <script src="../plugins/bootstrap-markdown/js/bootstrap-markdown.js"></script>
        <script
            src="../plugins/bootstrap-markdown/locale/bootstrap-markdown.zh.js"></script>
        <script src="../plugins/bootstrap-markdown/js/markdown.js"></script>
        <script src="../plugins/bootstrap-markdown/js/to-markdown.js"></script>
        <script src="../plugins/ckeditor/ckeditor.js"></script>
        <script src="../plugins/input-mask/jquery.inputmask.js"></script>
        <script
            src="../plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
        <script src="../plugins/input-mask/jquery.inputmask.extensions.js"></script>
        <script src="../plugins/datatables/jquery.dataTables.min.js"></script>
        <script src="../plugins/datatables/dataTables.bootstrap.min.js"></script>
        <script src="../plugins/chartjs/Chart.min.js"></script>
        <script src="../plugins/flot/jquery.flot.min.js"></script>
        <script src="../plugins/flot/jquery.flot.resize.min.js"></script>
        <script src="../plugins/flot/jquery.flot.pie.min.js"></script>
        <script src="../plugins/flot/jquery.flot.categories.min.js"></script>
        <script src="../plugins/ionslider/ion.rangeSlider.min.js"></script>
        <script src="../plugins/bootstrap-slider/bootstrap-slider.js"></script>
        <script>
            $(document).ready(function() {
                // 选择框
                $(".select2").select2();

                // WYSIHTML5编辑器
                $(".textarea").wysihtml5({
                    locale : 'zh-CN'
                });
            });

            // 设置激活菜单
            function setSidebarActive(tagUri) {
                var liObj = $("#" + tagUri);
                if (liObj.length > 0) {
                    liObj.parent().parent().addClass("active");
                    liObj.addClass("active");
                }
            }

            $(document)
                    .ready(
                            function() {

                                // 激活导航位置
                                setSidebarActive("admin-datalist");

                                // 列表按钮 
                                $("#dataList td input[type='checkbox']")
                                        .iCheck(
                                                {
                                                    checkboxClass : 'icheckbox_square-blue',
                                                    increaseArea : '20%'
                                                });
                                // 全选操作 
                                $("#selall")
                                        .click(
                                                function() {
                                                    var clicks = $(this).is(
                                                            ':checked');
                                                    if (!clicks) {
                                                        $(
                                                                "#dataList td input[type='checkbox']")
                                                                .iCheck(
                                                                        "uncheck");
                                                    } else {
                                                        $(
                                                                "#dataList td input[type='checkbox']")
                                                                .iCheck("check");
                                                    }
                                                    $(this).data("clicks",
                                                            !clicks);
                                                });
                            });
        </script>
</body>

</html>
package com.itheima.controlloer;

import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.RoleService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> userList = userService.list();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/saveUI")
    public ModelAndView saveUI(){
        ModelAndView modelAndView = new ModelAndView();
        List<Role> roleList = roleService.list();
        modelAndView.addObject("roleList",roleList);
        modelAndView.setViewName("user-add");
        return modelAndView;
    }

    @RequestMapping("/save")
    public String save(User user,Long[] roleIds){
        userService.save(user,roleIds);
        return "redirect:/user/list";
    }

    @RequestMapping("/del/{userId}")
    public String delete(@PathVariable("userId") Long userId){
        userService.del(userId);
        return "redirect:/user/list";
    }
}
package com.itheima.service;

import com.itheima.domain.User;
import java.util.List;

public interface UserService {

    public List<User> list();
    void save(User user, Long[] roleIds);
    void del(Long userId);
}
package com.itheima.service.impl;

import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import java.util.List;

public class UserServiceImpl implements UserService {

    private UserDao userDao;
    private RoleDao roleDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public List<User> list() {

        List<User> userList = userDao.findAll();
        //封装userList中的每一个User的roles数据
        for (User user : userList) {
            //获得user的id
            Long id = user.getId();
            //将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roles= roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }

    public void save(User user, Long[] roleIds) {
        //第一步:向sys_user表中存储数据
        Long userId = userDao.save(user);
        System.out.println("userId----"+userId);
        //第二步:向sys_user_role关系表中存储多条数据
        System.out.println("roleIds----"+roleIds);
        userDao.saveUserRoleRel(userId,roleIds);
    }

    public void del(Long userId) {
        //1、删除sys_user_role关系表
        userDao.delUserRoleRel(userId);
        //2、删除sys_user表
        userDao.del(userId);
    }
}
package com.itheima.dao;

import com.itheima.domain.User;
import java.util.List;

public interface UserDao {

    List<User> findAll();
    Long save(User user);
    void saveUserRoleRel(Long userId, Long[] roleIds);
    void delUserRoleRel(Long userId);
    void del(Long userId);
}
package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<User> findAll() {

        List<User> userList = jdbcTemplate.query("select * from sys_user", new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    public Long save(final User user) {
        //创建PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                //使用原始jdbc完成有个PreparedStatement的组建
                PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setString(2,user.getUsername());
                preparedStatement.setString(3,user.getEmail());
                preparedStatement.setString(4,user.getPassword());
                preparedStatement.setString(5,user.getPhoneNum());
                return preparedStatement;
            }
        };
        //创建keyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator,keyHolder);
        //获得生成的主键
        long userId = keyHolder.getKey().longValue();
        return userId;
    }

    public void saveUserRoleRel(Long userId, Long[] roleIds) {
        for (Long roleId : roleIds) {
            jdbcTemplate.update("insert into sys_user_role values(?,?)",userId,roleId);
        }
    }

    public void delUserRoleRel(Long userId) {
        jdbcTemplate.update("delete from sys_user_role where userId=?",userId);
    }

    public void del(Long userId) {
        jdbcTemplate.update("delete from sys_user where id=?",userId);
    }
}

  启动tomcat服务器,点击删除:

  

   “确定”删除:

  

    

  

 思考:UserServiceImpl类中del方法里面有两个操作,如果其中一个失败怎么办,考虑使用事务控制

posted on 2023-05-29 22:43  花溪月影  阅读(33)  评论(0编辑  收藏  举报