项目架构java在线教育项目实战 ,权限系统实战


项目架构java在线教育项目实战 ,权限系统实战

"${pageContext.request.contextPath}/static/plugins/easyui/uimaker/easyui.css">
  •   <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/plugins/easyui/uimaker/icon.css">
  •   <script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/easyui/jquery.min.js"></script>
  •   <script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/easyui/jquery.easyui.min.js"></script>
  •   <script type="text/javascript" src="${pageContext.request.contextPath}/static/plugins/easyui/easyui-lang-zh_CN.js"></script>
  •   <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/index.js"></script>
  • 3.编写body首页框架格式

    1.   class="easyui-layout">
    2.   <div data-options="region:'north'" style="height:100px; background: #ec4e00; padding: 20px 20px">
    3.   <img src="main_logo.png" alt="">
    4.   div>
    5.   <div data-options="region:'south'" style="height:50px; border-bottom: 3px solid #ec4e00">
    6.   <p align="center" style="font-size: 14px">撩课学院p>
    7.   div>
    8.   <div data-options="region:'west',split:true" style="width:300px;">
    9.   <div id="aa" class="easyui-accordion" data-options="fit:true">
    10.   <div title="菜单" data-options="iconCls:'icon-save',selected:true" style="overflow:auto;padding:10px;">
    11.  
    12.   <ul id="tree">ul>
    13.   div>
    14.   <div title="公告" data-options="iconCls:'icon-reload'" style="padding:10px;">
    15.   div>
    16.   div>
    17.   div>
    18.   <div data-options="region:'center'" style="background:#eee;">
    19.  
    20.   <div id="tabs" style="overflow: hidden" >
    21.   div>
    22.   div>
    23.   body>

    4.创建首页index.js引入

    1.   $(function () {
    2.   $("#tabs").tabs({
    3.   fit:true
    4.   })
    5.   $('#tree').tree({
    6.   url:'/getTreeData',
    7.   lines:true,
    8.   onSelect: function(node){
    9.   /*在添加之前, 做判断 判断这个标签是否存在 */
    10.   var exists = $("#tabs").tabs("exists",node.text);
    11.   if(exists){
    12.   /*存在,就让它选中*/
    13.   $("#tabs").tabs("select",node.text);
    14.   }else {
    15.   if (node.url !=''&& node.url !=null){
    16.   /*如果不存在 ,添加新标签*/
    17.   $("#tabs").tabs("add",{
    18.   title:node.text,
    19.   /*href:node.attributes.url,*/ /*href 引入的是body当中*/
    20.   content:"",
    21.   closable:true
    22.   })
    23.   }
    24.   }
    25.   },
    26.   onLoadSuccess: function (node, data) {
    27.   console.log(data[0].children[0].id);
    28.   if (data.length > 0) {
    29.   //找到第一个元素
    30.   var n = $('#tree').tree('find', data[0].children[0].id);
    31.   //调用选中事件
    32.   $('#tree').tree('select', n.target);
    33.   }
    34.   }
    35.    
    36.   });
    37.   });

    员工列表

    1.在tree当中指定跳转的地址--暂时用tree.json文件代替

    1.   [
    2.   {
    3.   "id": 1,
    4.   "text": "系统管理",
    5.   "children": [
    6.   {
    7.   "id":2,
    8.   "text": "员工管理",
    9.   "url": "/employee"
    10.   },
    11.   {
    12.   "id":3,
    13.   "text": "角色权限管理",
    14.   "url": "/role"
    15.   },
    16.   {
    17.   "id":4,
    18.   "text": "菜单管理",
    19.   "url": "/menu"
    20.    
    21.   }
    22.   ]
    23.   }
    24.   ]
    **index.js**
     
    1.   $(function () {
    2.   $("#tabs").tabs({
    3.   fit:true
    4.   })
    5.   $('#tree').tree({
    6.   url:"static/tree.json",
    7.   lines:true,
    8.   onSelect: function(node){
    9.   /*在添加之前, 做判断 判断这个标签是否存在 */
    10.   var exists = $("#tabs").tabs("exists",node.text);
    11.   if(exists){
    12.   /*存在,就让它选中*/
    13.   $("#tabs").tabs("select",node.text);
    14.   }else {
    15.   if (node.url !=''&& node.url !=null){
    16.   /*如果不存在 ,添加新标签*/
    17.   $("#tabs").tabs("add",{
    18.   title:node.text,
    19.   /*href:node.attributes.url,*/ /*href 引入的是body当中*/
    20.   content:"",
    21.   closable:true
    22.   })
    23.   }
    24.   }
    25.   }
    26.   });
    27.   });

    2.创建页面跳转控制器,接收请求跳转到Employee页面

    1.   @Controller
    2.   public class PageLocation {
    3.   @RequestMapping("/employee")
    4.   public String employee(){
    5.   return "employee";
    6.   }
    7.    
    8.   @RequestMapping("/department")
    9.   public String department(){
    10.   return "department";
    11.   }
    12.   }

    3.在Employee页面中引入公共的EasyUI相关js编写数据表格

    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/employee.js">script>
     

    4.创建Employee.js引入设置-数据表格

    数据加载

                **employee.js**
     
    1.   $(function () {
    2.   /*员式数据列表*/
    3.   $("#dg").datagrid({
    4.   url:"/employeeList",
    5.   columns:[[
    6.   {field:'username',title:'姓名',width:100,align:'center'},
    7.   {field:'inputtime',title:'入职时间',width:100,align:'center'},
    8.   {field:'tel',title:'电话',width:100,align:'center'},
    9.   {field:'email',title:'邮箱',width:100,align:'center'},
    10.   {field:'department',title:'部门',width:100,align:'center',formatter: function(value,row,index){
    11.   if (value){
    12.   return value.name;
    13.   }
    14.   }},
    15.   {field:'state',title:'状态',width:100,align:'center',formatter: function(value,row,index){
    16.   if(row.state){
    17.   return "在职";
    18.   }else {
    19.   return "离职"
    20.   }
    21.   }},
    22.   {field:'admin',title:'管理员',width:100,align:'center',formatter: function(value,row,index){
    23.   if(row.admin){
    24.   return "是";
    25.   }else {
    26.   return "否"
    27.   }
    28.   }},
    29.   ]],
    30.   fit:true,
    31.   fitColumns:true,
    32.   rownumbers:true,
    33.   pagination:true,
    34.   singleSelect:true,
    35.   striped:true,
    36.   toolbar:"#tb",
    37.   onClickRow:function (rowIndex,rowData) {
    38.   /*判断当前行是否是离职状态*/
    39.   if(!rowData.state){
    40.   /*离职,把离职按钮禁用*/
    41.   $("#delete").linkbutton("disable");
    42.   }else {
    43.   /*离职,把离职按钮启用*/
    44.   $("#delete").linkbutton("enable");
    45.   }
    46.   }
    47.   });
    48.   })

    控制层

    1.   @Controller
    2.   public class EmployeeController {
    3.   /*注入业务层*/
    4.   @Autowired
    5.   private EmployeeService employeeService;
    6.    
    7.   @RequestMapping("/employee")
    8.   public String employee(){
    9.   return "employee";
    10.   }
    11.    
    12.   @RequestMapping("/employeeList")
    13.   @ResponseBody
    14.   public PageListRes employeeList(QueryVo vo){
    15.   System.out.println(vo);
    16.   /*调用业务层查询员工*/
    17.   PageListRes pageListRes = employeeService.getEmployee(vo);
    18.   return pageListRes;
    19.   }
    20.   })

    业务层

    1.   @Service
    2.   @Transactional
    3.   public class EmployeeServiceImpl implements EmployeeService {
    4.    
    5.   @Autowired
    6.   private EmployeeMapper employeeMapper;
    7.    
    8.   @Override
    9.   public PageListRes getEmployee(QueryVo vo) {
    10.   /*调用mapper 查询员工 */
    11.   Page<Object> page = PageHelper.startPage(vo.getPage(), vo.getRows());
    12.   List<Employee> employees = employeeMapper.selectAll(vo);
    13.   /*封装成pageList*/
    14.   PageListRes pageListRes = new PageListRes();
    15.   pageListRes.setTotal(page.getTotal());
    16.   pageListRes.setRows(employees);
    17.   return pageListRes;
    18.   }
    19.   })
            日期格式化
     
    1.   @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    2.   @DateTimeFormat(pattern = "yyyy-MM-dd")
    3.   private Date inputtime;

    格式化状态和管理员

    5.创建部门表

    建表语句

    1.   CREATE TABLE `department` (
    2.   `id` bigint(20) NOT NULL,
    3.   `name` varchar(10) DEFAULT NULL COMMENT '部门名称 ',
    4.   `sn` varchar(20) DEFAULT NULL COMMENT '部门编号',
    5.   `manager_id` bigint(20) DEFAULT NULL,
    6.   `parent_id` bigint(20) DEFAULT NULL,
    7.   `state` tinyint(1) DEFAULT NULL,
    8.   PRIMARY KEY (`id`),
    9.   KEY `manager_id` (`manager_id`),
    10.   KEY `parent_id` (`parent_id`),
    11.   CONSTRAINT `department_ibfk_1` FOREIGN KEY (`manager_id`) REFERENCES `employee` (`id`),
    12.   CONSTRAINT `department_ibfk_2` FOREIGN KEY (`parent_id`) REFERENCES `department` (`id`)
    13.   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    employee表添加字段dept_id

    在代码生成器当中生成相关domain和mapper

    修改employee的domian

    1.   @Setter@Getter@ToString
    2.   public class Employee {
    3.   private Long id;
    4.   private String username;
    5.   private String password;
    6.   @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
    7.   @DateTimeFormat(pattern = "yyyy-MM-dd")
    8.   private Date inputtime;
    9.   private String tel;
    10.   private String email;
    11.   private Boolean state;
    12.   private Boolean admin;
    13.   private Department department;
    14.   }

    6.查询部门

    ? EmployeeMapper.xml

    1.   <?xml version="1.0" encoding="UTF-8" ?>
    2.   mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    3.   <mapper namespace="com.itlike.mapper.EmployeeMapper" >
    4.   <resultMap id="BaseResultMap" type="com.itlike.domain.Employee" >
    5.   <id column="id" property="id" jdbcType="BIGINT" />
    6.   <result column="username" property="username" jdbcType="VARCHAR" />
    7.   <result column="inputtime" property="inputtime" jdbcType="TIMESTAMP" />
    8.   <result column="tel" property="tel" jdbcType="VARCHAR" />
    9.   <result column="email" property="email" jdbcType="VARCHAR" />
    10.   <result column="state" property="state" jdbcType="BIT" />
    11.   <result column="admin" property="admin" jdbcType="BIT" />
    12.    
    13.   <association property="department" javaType="com.itlike.domain.Department" columnPrefix="d_">
    14.   <result property="id" column="id"/>
    15.   <result property="name" column="name"/>
    16.   association>
    17.    
    18.   resultMap>
    19.  
    20.   <select id="selectAll" resultMap="BaseResultMap" >
    21.   select
    22.   e.id,
    23.   e.username,
    24.   e.inputtime,
    25.   e.tel,
    26.   e.email,
    27.   e.state,
    28.   e.admin,
    29.   d.id as d_id,
    30.   d.`name` as d_name
    31.   from employee as e
    32.   LEFT JOIN department as d
    33.   ON e.dep_id = d.id
    34.   <include refid="where_sql"/>
    35.   order by e.id desc
    36.   select>
    37.   mapper>
    1.   $(function () {
    2.   /*员式数据列表*/
    3.   $("#dg").datagrid({
    4.   url:"/employeeList",
    5.   columns:[[
    6.   {field:'username',title:'姓名',width:100,align:'center'},
    7.   {field:'inputtime',title:'入职时间',width:100,align:'center'},
    8.   {field:'tel',title:'电话',width:100,align:'center'},
    9.   {field:'email',title:'邮箱',width:100,align:'center'},
    10.   {field:'department',title:'部门',width:100,align:'center',formatter: function(value,row,index){
    11.   if (value){
    12.   return value.name;
    13.   }
    14.   }},
    15.   {field:'state',title:'状态',width:100,align:'center',formatter: function(value,row,index){
    16.   if(row.state){
    17.   return "在职";
    18.   }else {
    19.   return "离职"
    20.   }
    21.   }},
    22.   {field:'admin',title:'管理员',width:100,align:'center',formatter: function(value,row,index){
    23.   if(row.admin){
    24.   return "是";
    25.   }else {
    26.   return "否"
    27.   }
    28.   }},
    29.   ]]
    30.   });
    31.   })

    7.列表添加工具栏目

    ? 1.添加标签

    1.   <div id="tb">
    2.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" id="add">添加a>
    3.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true" id="edit">编辑a>
    4.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" id="delete">删除a>
    5.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload',plain:true" id="reload">刷新a>
    6.   div>

    ? 2.处理Js
    ?

     toolbar: '#tb',
     

    8.添加对话框弹出

    对话框标签

    1.   <table align="center" style="border-spacing: 0px 10px">
    2.   <tr>
    3.   <td>用户名:td>
    4.   <td><input type="text" class="easyui-validatebox" data-options="required:true">td>
    5.   tr>
    6.   <tr>
    7.   <td>真实姓名:td>
    8.   <td><input type="text" class="easyui-validatebox" data-options="required:true">td>
    9.   tr>
    10.   <tr>
    11.   <td>手机:td>
    12.   <td><input type="text" class="easyui-validatebox" data-options="required:true">td>
    13.   tr>
    14.   <tr>
    15.   <td>邮箱:td>
    16.   <td><input type="text" class="easyui-validatebox" data-options="required:true,validType:'email'" >td>
    17.   tr>
    18.   <tr>
    19.   <td>入职日期:td>
    20.   <td><input type="text" class="easyui-datebox" required="required">td>
    21.   tr>
    22.   <tr>
    23.   <td>部门:td>
    24.   <td><select id="department">select>td>
    25.   tr>
    26.   <tr>
    27.   <td>是否管理员:td>
    28.   <td><select id="state">select>td>
    29.   tr>
    30.   table>

    部门列表展示

    1.   /*部门选择 下拉列表*/
    2.   $("#department").combobox({
    3.   width:150,
    4.   panelHeight:'auto',
    5.   editable:false,
    6.   url:'departList',
    7.   textField:'name',
    8.   valueField:'id',
    9.   onLoadSuccess:function () { /*数据加载完毕之后回调*/
    10.   $("#department").each(function(i){
    11.   var span = $(this).siblings("span")[i];
    12.   var targetInput = $(span).find("input:first");
    13.   if(targetInput){
    14.   $(targetInput).attr("placeholder", $(this).attr("placeholder"));
    15.   }
    16.   });
    17.   }
    18.   });

    设置placehode

    1.   $("#department").each(function(i){
    2.   var span = $(this).siblings("span")[i];
    3.   var targetInput = $(span).find("input:first");
    4.   if(targetInput){
    5.   $(targetInput).attr("placeholder", $(this).attr("placeholder"));
    6.   }
    7.   });

    是否管理员下拉列表展示

    1.   /*管理员下拉列表选择*/
    2.   $("#state").combobox({
    3.   width:150,
    4.   panelHeight:'auto',
    5.   textField:'label',
    6.   valueField:'value',
    7.   data:[{
    8.   label:'是',
    9.   value:'true'
    10.   },{
    11.   label:'否',
    12.   value:'false'
    13.   }]
    14.   });
    15.   $("#state").combobox({"select","否"});

    9.保存

    表单标签上填写name

    1.   <form id="employeeForm">
    2.   <%--添加一个隐藏域 编辑--%>
    3.   <input type="hidden" name="id">
    4.   <table align="center" style="border-spacing: 0px 10px">
    5.   <tr>
    6.   <td>用户名:td>
    7.   <td><input type="text" name="username" class="easyui-validatebox" data-options="required:true">td>
    8.   tr>
    9.   <tr id="password">
    10.   <td>密码:td>
    11.   <td><input type="text" name="password" class="easyui-validatebox">td>
    12.   tr>
    13.   <tr>
    14.   <td>手机:td>
    15.   <td><input type="text" name="tel" class="easyui-validatebox" >td>
    16.   tr>
    17.   <tr>
    18.   <td>邮箱:td>
    19.   <td><input type="text" name="email" class="easyui-validatebox" >td>
    20.   tr>
    21.   <tr>
    22.   <td>入职日期:td>
    23.   <td><input type="text" name="inputtime" class="easyui-datebox">td>
    24.   tr>
    25.   <tr>
    26.   <td>部门:td>
    27.   <td><input id="department" name="department.id" placeholder="请选择部门"/>td>
    28.   tr>
    29.   <tr>
    30.   <td>是否管理员:td>
    31.   <td><input id="state" name="admin" placeholder="是否为管理员"/>td>
    32.   tr>
    33.   <tr>
    34.   <td>选择角色:td>
    35.   <td><input id="role" name="role.rid" placeholder="请选择角色"/>td>
    36.   tr>
    37.   table>
    38.   form>

    下拉列表设置默认值时, 默认value也要设置上去

    保存时判断添加还是编辑

    监听保存按钮,提交表单

    1.   /*对话框*/
    2.   $("#dialog").dialog({
    3.   width:350,
    4.   height:400,
    5.   closed:true,
    6.   buttons:[{
    7.   text:'保存',
    8.   handler:function(){
    9.    
    10.   /*判断当前是添加 还是编辑*/
    11.   var id = $("[name='id']").val();
    12.   var url;
    13.   if(id){
    14.   /*编辑*/
    15.   url = "updateEmployee";
    16.   }else {
    17.   /*添加*/
    18.   url= "saveEmployee";
    19.   }
    20.    
    21.   /*提交表单*/
    22.   $("#employeeForm").form("submit",{
    23.   url:url,
    24.   onSubmit:function(param){
    25.   /*获取选中的角色*/
    26.   var values = $("#role").combobox("getValues");
    27.   for(var i = 0; i < values.length; i++){
    28.   var rid = values[i];
    29.   param["roles["+i+"].rid"] = rid;
    30.   }
    31.   },
    32.   success:function (data) {
    33.   data = $.parseJSON(data);
    34.   if (data.success){
    35.   $.messager.alert("温馨提示",data.msg);
    36.   /*关闭对话框 */
    37.   $("#dialog").dialog("close");
    38.   /*重新加载数据表格*/
    39.   $("#dg").datagrid("reload");
    40.   } else {
    41.   $.messager.alert("温馨提示",data.msg);
    42.   }
    43.   }
    44.   });
    45.   }
    46.   },{
    47.   text:'关闭',
    48.   handler:function(){
    49.   $("#dialog").dialog("close");
    50.   }
    51.   }]
    52.   });

    10.编辑

    监听编辑按钮点击

    1.   /*监听编辑按钮点击*/
    2.   $("#edit").click(function () {
    3.   /*获取当前选中的行*/
    4.   var rowData = $("#dg").datagrid("getSelected");
    5.   console.log(rowData);
    6.   if(!rowData){
    7.   $.messager.alert("提示","选择一行数据进行编辑");
    8.   return;
    9.   }
    10.   /*取消密码验证*/
    11.   $("[name='password']").validatebox({required:false});
    12.   $("#password").hide();
    13.   /*弹出对话框*/
    14.   $("#dialog").dialog("setTitle","编辑员工");
    15.   $("#dialog").dialog("open");
    16.   /*回显部门*/
    17.   rowData["department.id"] = rowData["department"].id;
    18.   /*回显管理员*/
    19.   rowData["admin"] = rowData["admin"]+"";
    20.   /*回显角色*/
    21.   /*根据当前用户的id,查出对应的角色*/
    22.   $.get("/getRoleByEid?id="+rowData.id,function (data) {
    23.   /*设置下拉列表数据回显*/
    24.   $("#role").combobox("setValues",data);
    25.   });
    26.    
    27.   /*选中数据的回示*/
    28.   $("#employeeForm").form("load",rowData);
    29.    
    30.   });

    更新业务逻辑

    1.   /*接收更新员工请求*/
    2.   @RequestMapping("/updateEmployee")
    3.   @ResponseBody
    4.   @RequiresPermissions("employee:edit")
    5.   public AjaxRes updateEmployee(Employee employee){
    6.   AjaxRes ajaxRes = new AjaxRes();
    7.   try {
    8.   /*调用业务层,更新员工*/
    9.   employeeService.updateEmployee(employee);
    10.   ajaxRes.setMsg("更新成功");
    11.   ajaxRes.setSuccess(true);
    12.   }catch (Exception e){
    13.   ajaxRes.setSuccess(false);
    14.   ajaxRes.setMsg("更新失败");
    15.   }
    16.   return ajaxRes;
    17.   }

    11.离职

    离职按钮点击

    1.   /*设置离职按钮点击*/
    2.   $("#delete").click(function () {
    3.   /*获取当前选中的行*/
    4.   var rowData = $("#dg").datagrid("getSelected");
    5.   console.log(rowData);
    6.   if(!rowData){
    7.   $.messager.alert("提示","选择一行数据进行编辑");
    8.   return;
    9.   }
    10.   /*提醒用户,是否做离职操作*/
    11.   $.messager.confirm("确认","是否做离职操作",function (res) {
    12.   if(res){
    13.   /*做离职操作*/
    14.   $.get("/updateState?id="+rowData.id,function (data) {
    15.   if (data.success){
    16.   $.messager.alert("温馨提示",data.msg);
    17.   /*重新加载数据表格*/
    18.   $("#dg").datagrid("reload");
    19.   } else {
    20.   $.messager.alert("温馨提示",data.msg);
    21.   }
    22.    
    23.   });
    24.   }
    25.   });
    26.   });

    业务处理

    1.   /*接收离职操作请求*/
    2.   @RequestMapping("/updateState")
    3.   @ResponseBody
    4.   @RequiresPermissions("employee:delete")
    5.   public AjaxRes updateState(Long id){
    6.   AjaxRes ajaxRes = new AjaxRes();
    7.   try {
    8.   /*调用业务层,设置员工离职状态*/
    9.   employeeService.updateState(id);
    10.   ajaxRes.setMsg("更新成功");
    11.   ajaxRes.setSuccess(true);
    12.   }catch (Exception e){
    13.   System.out.println(e);
    14.   ajaxRes.setSuccess(false);
    15.   ajaxRes.setMsg("更新失败");
    16.   }
    17.   return ajaxRes;
    18.   }

    12.离职按钮禁用

    给数据表格绑定选中事件

    1.   /*员式数据列表*/
    2.   $("#dg").datagrid({
    3.   url:"/employeeList",
    4.   columns:[[
    5.   {field:'username',title:'姓名',width:100,align:'center'},
    6.   {field:'inputtime',title:'入职时间',width:100,align:'center'},
    7.   {field:'tel',title:'电话',width:100,align:'center'},
    8.   {field:'email',title:'邮箱',width:100,align:'center'},
    9.   {field:'department',title:'部门',width:100,align:'center',formatter: function(value,row,index){
    10.   if (value){
    11.   return value.name;
    12.   }
    13.   }},
    14.   {field:'state',title:'状态',width:100,align:'center',formatter: function(value,row,index){
    15.   if(row.state){
    16.   return "在职";
    17.   }else {
    18.   return "离职"
    19.   }
    20.   }},
    21.   {field:'admin',title:'管理员',width:100,align:'center',formatter: function(value,row,index){
    22.   if(row.admin){
    23.   return "是";
    24.   }else {
    25.   return "否"
    26.   }
    27.   }},
    28.   ]],
    29.   fit:true,
    30.   fitColumns:true,
    31.   rownumbers:true,
    32.   pagination:true,
    33.   singleSelect:true,
    34.   striped:true,
    35.   toolbar:"#tb",
    36.   onClickRow:function (rowIndex,rowData) {
    37.   /*判断当前行是否是离职状态*/
    38.   if(!rowData.state){
    39.   /*离职,把离职按钮禁用*/
    40.   $("#delete").linkbutton("disable");
    41.   }else {
    42.   /*离职,把离职按钮启用*/
    43.   $("#delete").linkbutton("enable");
    44.   }
    45.   }
    46.   });

    添加按钮js插件(记得是因为EasyUI带有小bug)

    ? base.js

    1.   /**
    2.   * linkbutton方法扩展
    3.   * @param {Object} jq
    4.   */
    5.   $.extend($.fn.linkbutton.methods, {
    6.   /**
    7.   * 激活选项(覆盖重写)
    8.   * @param {Object} jq
    9.   */
    10.   enable: function(jq){
    11.   return jq.each(function(){
    12.   var state = $.data(this, 'linkbutton');
    13.    
    14.   if ($(this).hasClass('l-btn-disabled')) {
    15.   var itemData = state._eventsStore;
    16.   //恢复超链接
    17.   if (itemData.href) {
    18.   $(this).attr("href", itemData.href);
    19.   }
    20.   //回复点击事件
    21.   if (itemData.onclicks) {
    22.   for (var j = 0; j < itemData.onclicks.length; j++) {
    23.   $(this).bind('click', itemData.onclicks[j]);
    24.   }
    25.   }
    26.   //设置target为null,清空存储的事件处理程序
    27.   itemData.target = null;
    28.   itemData.onclicks = [];
    29.   $(this).removeClass('l-btn-disabled');
    30.   }
    31.   });
    32.   },
    33.   /**
    34.   * 禁用选项(覆盖重写)
    35.   * @param {Object} jq
    36.   */
    37.   disable: function(jq){
    38.   return jq.each(function(){
    39.   var state = $.data(this, 'linkbutton');
    40.   if (!state._eventsStore)
    41.   state._eventsStore = {};
    42.   if (!$(this).hasClass('l-btn-disabled')) {
    43.   var eventsStore = {};
    44.   eventsStore.target = this;
    45.   eventsStore.onclicks = [];
    46.   //处理超链接
    47.   var strHref = $(this).attr("href");
    48.   if (strHref) {
    49.   eventsStore.href = strHref;
    50.   $(this).attr("href", "javascript:void(0)");
    51.   }
    52.   //处理直接耦合绑定到onclick属性上的事件
    53.   var onclickStr = $(this).attr("onclick");
    54.   if (onclickStr && onclickStr != "") {
    55.   eventsStore.onclicks[eventsStore.onclicks.length] = new Function(onclickStr);
    56.   $(this).attr("onclick", "");
    57.   }
    58.   //处理使用jquery绑定的事件
    59.   var eventDatas = $(this).data("events") || $._data(this, 'events');
    60.   if (eventDatas["click"]) {
    61.   var eventData = eventDatas["click"];
    62.   for (var i = 0; i < eventData.length; i++) {
    63.   if (eventData[i].namespace != "menu") {
    64.   eventsStore.onclicks[eventsStore.onclicks.length] = eventData[i]["handler"];
    65.   $(this).unbind('click', eventData[i]["handler"]);
    66.   i--;
    67.   }
    68.   }
    69.   }
    70.   state._eventsStore = eventsStore;
    71.   $(this).addClass('l-btn-disabled');
    72.   }
    73.   });
    74.   }
    75.   });

    13.分页控制

    EasyUI中可以自动的提交分页参数直接接收分页参数

    1.   @RequestMapping("/employeeList")
    2.   @ResponseBody
    3.   public PageListRes employeeList(QueryVo vo){
    4.   System.out.println(vo);
    5.   /*调用业务层查询员工*/
    6.   PageListRes pageListRes = employeeService.getEmployee(vo);
    7.   return pageListRes;
    8.   }

    业务处理

    1.   @Override
    2.   public PageListRes getEmployee(QueryVo vo) {
    3.   /*调用mapper 查询员工 */
    4.   Page<Object> page = PageHelper.startPage(vo.getPage(), vo.getRows());
    5.   List<Employee> employees = employeeMapper.selectAll(vo);
    6.   /*封装成pageList*/
    7.   PageListRes pageListRes = new PageListRes();
    8.   pageListRes.setTotal(page.getTotal());
    9.   pageListRes.setRows(employees);
    10.   return pageListRes;
    11.   }

    14.高级查询

    在toolbar上添加搜索框

    1.   <input type="text" name="keyword" style="width: 200px; height: 30px;padding-left: 5px;">
    2.   <a class="easyui-linkbutton" iconCls="icon-search" id="searchbtn">查询a>

    监听搜索点击

    1.   /*监听搜索按钮点击*/
    2.   $("#searchbtn").click(function () {
    3.   /*获取搜索的内容*/
    4.   var keyword = $("[name='keyword']").val();
    5.   /*重新加载列表 把参数keyword传过去*/
    6.   $("#dg").datagrid("load",{keyword:keyword});
    7.   });

    接收参数处理

    1.   @Setter@Getter@ToString
    2.   public class QueryVo {
    3.   private int page;
    4.   private int rows;
    5.   private String keyword;
    6.   }
    1.   @Override
    2.   public PageListRes getEmployee(QueryVo vo) {
    3.   /*调用mapper 查询员工 */
    4.   Page<Object> page = PageHelper.startPage(vo.getPage(), vo.getRows());
    5.   List<Employee> employees = employeeMapper.selectAll(vo);
    6.   /*封装成pageList*/
    7.   PageListRes pageListRes = new PageListRes();
    8.   pageListRes.setTotal(page.getTotal());
    9.   pageListRes.setRows(employees);
    10.   return pageListRes;
    11.   }
    1.   "where_sql">
    2.   <where>
    3.   <if test="keyword !=null and keyword !=''">
    4.   and e.username like concat('%',#{keyword},'%')
    5.   or e.tel like concat('%',#{keyword},'%')
    6.   or e.email like concat('%',#{keyword},'%')
    7.   if>
    8.   where>
    9.  
    10.    
    11.  
    12.   <select id="selectAll" resultMap="BaseResultMap" >
    13.   select
    14.   e.id,
    15.   e.username,
    16.   e.inputtime,
    17.   e.tel,
    18.   e.email,
    19.   e.state,
    20.   e.admin,
    21.   d.id as d_id,
    22.   d.`name` as d_name
    23.   from employee as e
    24.   LEFT JOIN department as d
    25.   ON e.dep_id = d.id
    26.   "where_sql"/>
    27.   order by e.id desc
    28.   select>

    添加权限

    1.建立角色与权限的表

    为多对多关系

    • 角色表
    1.   CREATE TABLE `employee` (
    2.   `id` bigint(20) NOT NULL AUTO_INCREMENT,
    3.   `username` varchar(50) DEFAULT NULL,
    4.   `inputtime` datetime DEFAULT NULL,
    5.   `tel` varchar(20) DEFAULT NULL,
    6.   `email` varchar(50) DEFAULT NULL,
    7.   `state` tinyint(1) DEFAULT NULL,
    8.   `admin` tinyint(1) DEFAULT NULL,
    9.   `dep_id` bigint(20) DEFAULT NULL,
    10.   `password` varchar(50) DEFAULT NULL,
    11.   PRIMARY KEY (`id`),
    12.   KEY `dep_id` (`dep_id`),
    13.   CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`dep_id`) REFERENCES `department` (`id`)
    14.   ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;
    • 权限表
    1.   CREATE TABLE `permission` (
    2.   `pid` bigint(20) NOT NULL,
    3.   `pname` varchar(50) DEFAULT NULL,
    4.   `presource` varchar(50) DEFAULT NULL,
    5.   PRIMARY KEY (`pid`)
    6.   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    • 角色与权限中间表
    1.   CREATE TABLE `employee_role_rel` (
    2.   `eid` bigint(20) NOT NULL,
    3.   `rid` bigint(20) NOT NULL,
    4.   PRIMARY KEY (`eid`,`rid`),
    5.   KEY `rid` (`rid`),
    6.   CONSTRAINT `employee_role_rel_ibfk_1` FOREIGN KEY (`eid`) REFERENCES `employee` (`id`),
    7.   CONSTRAINT `employee_role_rel_ibfk_2` FOREIGN KEY (`rid`) REFERENCES `role` (`rid`)
    8.   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    使用代码生成器生成相关mapper

    2.建立角色页面

    角色数据列表

    1.   <table id="emp_dg">table>
    2.   <div id="toolbar">
    3.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" id="add">添加a>
    4.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true" id="edit">编辑a>
    5.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" id="remove">离职a>
    6.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload',plain:true" id="reload">刷新a>
    7.   div>

    添加角色权限对话框

    1.   <div id="dialog">
    2.   <form id="myform">
    3.   <table align="center" style="border-spacing: 20px 30px">
    4.   <input type="hidden" name="id">
    5.   <tr align="center">
    6.   <td>角色编号: <input type="text" name="username" class="easyui-validatebox" >td>
    7.   <td>角色名称: <input type="text" name="username" class="easyui-validatebox" >td>
    8.   tr>
    9.   <tr>
    10.   <td><div id="role_data1">div>td>
    11.   <td><div id="role_data2">div>td>
    12.   tr>
    13.   table>
    14.   form>
    15.   div>

    3.加载权限数据实现点击添加权限,点击删除权限

    1.   /*角色数据列表*/
    2.   $("#role_dg").datagrid({
    3.   url:"/getRoles",
    4.   columns:[[
    5.   {field:'rnum',title:'角色编号',width:100,align:'center'},
    6.   {field:'rname',title:'角色名称',width:100,align:'center'},
    7.   ]],
    8.   fit:true,
    9.   fitColumns:true,
    10.   rownumbers:true,
    11.   pagination:true,
    12.   singleSelect:true,
    13.   striped:true,
    14.   toolbar:"#toolbar",
    15.   });
    16.    
    17.   /*权限列表*/
    18.   $("#role_data1").datagrid({
    19.   title:"所有权限",
    20.   width:250,
    21.   height:400,
    22.   fitColumns:true,
    23.   singleSelect:true,
    24.   url:'/permissionList',
    25.   columns:[[
    26.   {field:'pname',title:'权限名称',width:100,align:'center'},
    27.   ]],
    28.   onClickRow:function (rowIndex,rowData) {/*点击一行时,回调*/
    29.    
    30.   /*判断是否已经存在该权限*/
    31.   /*取出所有的已选权限*/
    32.   var allRows = $("#role_data2").datagrid("getRows");
    33.   /*取出每一个进行判断*/
    34.   for(var i = 0; ilength; i++){
    35.   /*取出每一行*/
    36.   var row = allRows[i];
    37.   if(rowData.pid == row.pid){/*已经存在该权限*/
    38.   /*让已经存在权限成为选中的状态*/
    39.   /*获取已经成为选中状态当前角标*/
    40.   var index = $("#role_data2").datagrid("getRowIndex",row);
    41.   /*让该行成为选中状态*/
    42.   $("#role_data2").datagrid("selectRow",index);
    43.   return;
    44.   }
    45.   }
    46.    
    47.   /*把当前选中的,添加到已选权限*/
    48.   $("#role_data2").datagrid("appendRow",rowData);
    49.   }
    50.   });
    51.    
    52.   /*选中权限列表*/
    53.   $("#role_data2").datagrid({
    54.   title:"已选权限",
    55.   width:250,
    56.   height:400,
    57.   singleSelect:true,
    58.   fitColumns:true,
    59.   columns:[[
    60.   {field:'pname',title:'权限名称',width:100,align:'center'},
    61.   ]],
    62.   onClickRow:function (rowIndex,rowData) {
    63.   /*删除当中选中的一行*/
    64.   $("#role_data2").datagrid("deleteRow",rowIndex);
    65.   }
    66.   });

    4.添加角色权限

    定义角色权限关系:一个角色有多个权限

    1.   @Getter@Setter@ToString
    2.   public class Role {
    3.   private Long rid;
    4.   private String rnum;
    5.   private String rname;
    6.    
    7.   /*一个角色可以有多个权限*/
    8.   private List<Permission> permissions = new ArrayList<>();
    9.    
    10.   }

    点击保存时,如果没有隐藏字段id,则为添加操作

    保存时, 参数传递;默认只传递input中的内容,还需要在提交表单时, 把添加的权限信息提交过去

    1.   /*添加/编辑对话框*/
    2.   $("#dialog").dialog({
    3.   width:600,
    4.   height:650,
    5.   buttons:[{
    6.   text:'保存',
    7.   handler:function(){
    8.    
    9.   /*判断当前是保存操作还是编辑操作*/
    10.   var rid = $("[name='rid']").val();
    11.   var url;
    12.   if(rid){
    13.   /*编辑*/
    14.   url="updateRole"
    15.   }else {
    16.   /*保存*/
    17.   url="saveRole";
    18.   }
    19.    
    20.   /*提交表单*/
    21.   $("#myform").form("submit",{
    22.   url:url,
    23.   onSubmit:function(param){ /*传递额外参数 已选择的权限*/
    24.    
    25.   /*获取已经选择的权限*/
    26.   var allRows = $("#role_data2").datagrid("getRows");
    27.   /*遍历出每一个权限*/
    28.   for(var i = 0; i< allRows.length; i++){
    29.   /*取出每一个权限 */
    30.   var row = allRows[i];
    31.   /*给它封装到集合中*/
    32.   param["permissions["+i+"].pid"] = row.pid;
    33.   }
    34.    
    35.   },
    36.   success:function (data) {
    37.   data = $.parseJSON(data);
    38.   if (data.success){
    39.   $.messager.alert("温馨提示",data.msg);
    40.   /*关闭对话框 */
    41.   $("#dialog").dialog("close");
    42.   /*重新加载数据表格*/
    43.   $("#role_dg").datagrid("reload");
    44.   } else {
    45.   $.messager.alert("温馨提示",data.msg);
    46.   }
    47.   }
    48.   });
    49.    
    50.   }
    51.   },{
    52.   text:'关闭',
    53.   handler:function(){
    54.   $("#dialog").dialog("close");
    55.   }
    56.   }],
    57.   closed:true
    58.   });

    接收参数,保存角色与权限

    1.   /*接收 保存角色请求地址*/
    2.   @RequestMapping("/saveRole")
    3.   @ResponseBody
    4.   public AjaxRes saveRole(Role role){
    5.   AjaxRes ajaxRes = new AjaxRes();
    6.   try {
    7.   /*调用业务层, 保存角色和权限*/
    8.   roleService.saveRole(role);
    9.   ajaxRes.setMsg("保存成功");
    10.   ajaxRes.setSuccess(true);
    11.   }catch (Exception e){
    12.   ajaxRes.setSuccess(false);
    13.   ajaxRes.setMsg("保存失败");
    14.   }
    15.   return ajaxRes;
    16.    
    17.   }
    1.   @Override
    2.   public void saveRole(Role role) {
    3.   /*1.保存角色*/
    4.   roleMapper.insert(role);
    5.   /*2.保存角色与权限之间关系*/
    6.   for (Permission permission : role.getPermissions()) {
    7.   roleMapper.insertRoleAndPermissionRel(role.getRid(),permission.getPid());
    8.   }
    9.    
    10.   }

    5.角色列表

    1.   /*角色数据列表*/
    2.   $("#role_dg").datagrid({
    3.   url:"/getRoles",
    4.   columns:[[
    5.   {field:'rnum',title:'角色编号',width:100,align:'center'},
    6.   {field:'rname',title:'角色名称',width:100,align:'center'},
    7.   ]],
    8.   fit:true,
    9.   fitColumns:true,
    10.   rownumbers:true,
    11.   pagination:true,
    12.   singleSelect:true,
    13.   striped:true,
    14.   toolbar:"#toolbar",
    15.   });

    6.编辑角色权限

    编辑回显

    1.   /*监听编辑点击*/
    2.   $("#edit").click(function () {
    3.   /*获取当前选中的行*/
    4.   var rowData = $("#role_dg").datagrid("getSelected");
    5.   console.log(rowData);
    6.   if(!rowData){
    7.   $.messager.alert("提示","选择一行数据进行编辑");
    8.   return;
    9.   }
    10.    
    11.   /*加载当前角色下的权限*/
    12.   var options = $("#role_data2").datagrid("options");
    13.   options.url = "/getPermissionByRid?rid="+rowData.rid;
    14.   /*重新加载数据*/
    15.   $("#role_data2").datagrid("load");
    16.    
    17.   /*选中数据的回示*/
    18.   $("#myform").form("load",rowData);
    19.   /*设置标题*/
    20.   $("#dialog").dialog("setTitle","编辑角色");
    21.   /*打开对话框 */
    22.   $("#dialog").dialog("open");
    23.   });

    添加时清空数据

    1.   /*添加角色*/
    2.   $("#add").click(function () {
    3.   /*清空表单*/
    4.   $("#myform").form("clear");
    5.   /*清空已选权限*/
    6.   $("#role_data2").datagrid("loadData",{rows:[]});
    7.   /*设置标题*/
    8.   $("#dialog").dialog("setTitle","添加角色");
    9.   /*打开对话框 */
    10.   $("#dialog").dialog("open");
    11.   });

     

    ?
    ?
    ?

    打破关系重新保存

    1.   /*更新角色*/
    2.   @Override
    3.   public void updateRole(Role role) {
    4.    
    5.   /*打破角色与权限之间的之前关系*/
    6.   roleMapper.deletePermissionRel(role.getRid());
    7.   /*更新角色*/
    8.   roleMapper.updateByPrimaryKey(role);
    9.   /*重新建立与权限的关系*/
    10.    
    11.   /*重新保存角色与权限之间关系*/
    12.   for (Permission permission : role.getPermissions()) {
    13.   roleMapper.insertRoleAndPermissionRel(role.getRid(),permission.getPid());
    14.   }
    15.   }

    5.删除角色权限

    监听删除按钮

    1.   /*监听删除点击*/
    2.   $("#remove").click(function () {
    3.   /*获取当前选中的行*/
    4.   var rowData = $("#role_dg").datagrid("getSelected");
    5.   console.log(rowData);
    6.   if(!rowData){
    7.   $.messager.alert("提示","选择一行数据进行删除");
    8.   return;
    9.   }
    10.   $.get("deleteRole?rid="+rowData.rid,function (data) {
    11.   if (data.success){
    12.   $.messager.alert("温馨提示",data.msg);
    13.   /*重新加载数据表格*/
    14.   $("#role_dg").datagrid("reload");
    15.   } else {
    16.   $.messager.alert("温馨提示",data.msg);
    17.   }
    18.   });
    19.   });

    处理业务逻辑

    1.   /*接收删除的请求*/
    2.   @RequestMapping("/deleteRole")
    3.   @ResponseBody
    4.   public AjaxRes deleteRole(Long rid){
    5.   AjaxRes ajaxRes = new AjaxRes();
    6.   try {
    7.   /*调用删除角色的业务*/
    8.   roleService.deleteRole(rid);
    9.   ajaxRes.setMsg("删除角色成功");
    10.   ajaxRes.setSuccess(true);
    11.   }catch (Exception e){
    12.   ajaxRes.setSuccess(false);
    13.   ajaxRes.setMsg("删除角色失败");
    14.   }
    15.   return ajaxRes;
    16.   }
    1.   /*删除角色的业务*/
    2.   @Override
    3.   public void deleteRole(Long rid) {
    4.   /*1.删除关联的权限*/
    5.   roleMapper.deletePermissionRel(rid);
    6.   /*2.删除对应的角色*/
    7.   roleMapper.deleteByPrimaryKey(rid);
    8.   }

    6.员工添加角色

    添加员工时, 添加角色下拉列表

    1.   /*回显角色*/
    2.   /*根据当前用户的id,查出对应的角色*/
    3.   $.get("/getRoleByEid?id="+rowData.id,function (data) {
    4.   /*设置下拉列表数据回显*/
    5.   $("#role").combobox("setValues",data);
    6.   });

    保存时, 保存时传递角色信息

    1.   /*提交表单*/
    2.   $("#employeeForm").form("submit",{
    3.   url:saveEmployee,
    4.   onSubmit:function(param){
    5.   /*获取选中的角色*/
    6.   var values = $("#role").combobox("getValues");
    7.   for(var i = 0; i < values.length; i++){
    8.   var rid = values[i];
    9.   param["roles["+i+"].rid"] = rid;
    10.   }
    11.   },
    12.   success:function (data) {
    13.   data = $.parseJSON(data);
    14.   if (data.success){
    15.   $.messager.alert("温馨提示",data.msg);
    16.   /*关闭对话框 */
    17.   $("#dialog").dialog("close");
    18.   /*重新加载数据表格*/
    19.   $("#dg").datagrid("reload");
    20.   } else {
    21.   $.messager.alert("温馨提示",data.msg);
    22.   }
    23.   }
    24.   });

    ?
    ?

    7.员工编辑

    回显数据

    1.   /*监听编辑按钮点击*/
    2.   $("#edit").click(function () {
    3.   /*获取当前选中的行*/
    4.   var rowData = $("#dg").datagrid("getSelected");
    5.   console.log(rowData);
    6.   if(!rowData){
    7.   $.messager.alert("提示","选择一行数据进行编辑");
    8.   return;
    9.   }
    10.   /*取消密码验证*/
    11.   $("[name='password']").validatebox({required:false});
    12.   $("#password").hide();
    13.   /*弹出对话框*/
    14.   $("#dialog").dialog("setTitle","编辑员工");
    15.   $("#dialog").dialog("open");
    16.   /*回显部门*/
    17.   // 当rowData["department"]为空时,会异常
    18.   if(rowData["department"] != null)
    19.   {
    20.   rowData["department.id"] = rowData["department"].id;
    21.   }
    22.   else
    23.   rowData["department.id"] = rowData["department"]+"";
    24.   /*回显管理员*/
    25.   rowData["admin"] = rowData["admin"]+"";
    26.   /*回显角色*/
    27.   /*根据当前用户的id,查出对应的角色*/
    28.   $.get("/getRoleByEid?id="+rowData.id,function (data) {
    29.   /*设置下拉列表数据回显*/
    30.   $("#role").combobox("setValues",data);
    31.   });
    32.    
    33.   /*选中数据的回示*/
    34.   $("#employeeForm").form("load",rowData);
    35.    
    36.   });

    ?
    ?

    ? 保存编辑

    1.   /*更新员工*/
    2.   @Override
    3.   public void updateEmployee(Employee employee) {
    4.   /*打破与角色之间关系*/
    5.   employeeMapper.deleteRoleRel(employee.getId());
    6.   /*更新员工*/
    7.   employeeMapper.updateByPrimaryKey(employee);
    8.   /*重新建立角色的关系*/
    9.   for (Role role : employee.getRoles()) {
    10.   employeeMapper.insertEmployeeAndRoleRel(employee.getId(),role.getRid());
    11.   }
    12.   }

    权限控制

    登录认证

    ? 整合Shiro(添加pom依赖)

    1.   <dependency>
    2.   <groupId>commons-logginggroupId>
    3.   <artifactId>commons-loggingartifactId>
    4.   <version>1.2version>
    5.   dependency>
    6.   <dependency>
    7.   <groupId>org.slf4jgroupId>
    8.   <artifactId>slf4j-nopartifactId>
    9.   <version>1.7.24version>
    10.   dependency>
    11.   <dependency>
    12.   <groupId>commons-collectionsgroupId>
    13.   <artifactId>commons-collectionsartifactId>
    14.   <version>3.2.1version>
    15.   dependency>
    16.   <dependency>
    17.   <groupId>org.apache.shirogroupId>
    18.   <artifactId>shiro-coreartifactId>
    19.   <version>1.4.0version>
    20.   dependency>
    21.   <dependency>
    22.   <groupId>org.apache.shirogroupId>
    23.   <artifactId>shiro-webartifactId>
    24.   <version>1.4.0version>
    25.   dependency>
    26.   <dependency>
    27.   <groupId>org.apache.shirogroupId>
    28.   <artifactId>shiro-ehcacheartifactId>
    29.   <version>1.4.0version>
    30.   dependency>
    31.   <dependency>
    32.   <groupId>org.apache.shirogroupId>
    33.   <artifactId>shiro-springartifactId>
    34.   <version>1.4.0version>
    35.   dependency>

    1.登录拦截,如果没有登录,跳转到登录页面

    ? 1.在web.xml当中配置过滤器拦截所有请求,进行处理
    ?

    1.  
    2.   <filter>
    3.   <filter-name>shiroFilterfilter-name>
    4.   <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
    5.  
    6.   <init-param>
    7.   <param-name>targetFilterLifecycleparam-name>
    8.   <param-value>trueparam-value>
    9.   init-param>
    10.   filter>
    11.    
    12.   <filter-mapping>
    13.   <filter-name>shiroFilterfilter-name>
    14.   <url-pattern>/*url-pattern>
    15.   filter-mapping>

    ? 2.在spring当中配置shiro过滤器和安全管理器
    ?
    ?

    1.  
    2.   <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    3.   <property name="securityManager" ref="securityManager">property>
    4.    
    5.  
    6.   <property name="filterChainDefinitions">
    7.   <value>
    8.   /static/** = anon
    9.   /login.jsp = anon
    10.   /**=authc
    11.   value>
    12.   property>
    13.   bean>
    14.    
    15.  
    16.   <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">bean>

    2.登录认证流程

    ? 1.表单发送请求
    ?

    1.   $(function () {
    2.   $("#loginBtn").click(function () {
    3.   /*Ajax发送请求, 是没有办法跳转服务当中的请求
    4.   * 只能通过在浏览器当中来跳转
    5.   * */
    6.   $.post("/login",$("form").serialize(),function (data) {
    7.   /*把data json格式的字符串 转成 json 数据*/
    8.   data = $.parseJSON(data);
    9.   if (data.success){
    10.   /*跳转到首页*/
    11.   window.location.href = "/index.jsp"
    12.   } else {
    13.   alert(data.msg);
    14.   }
    15.   });
    16.   });
    17.   });

    ? 2.指定登录认证路径

    1.  
    2.   <property name="loginUrl" value="/login" />

    ? 3.创建登录realm和重新配置过滤器

    1.   public class EmployeeRealm extends AuthorizingRealm {
    2.    
    3.   @Autowired
    4.   private EmployeeService employeeService;
    5.    
    6.   /*认证*/
    7.   @Override
    8.   protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    9.   System.out.println("来到了认证-------");
    10.   /*获取身份信息*/
    11.   String username = (String)token.getPrincipal();
    12.   System.out.println(username);
    13.   /*根据用户名当中查询有没有当前用户*/
    14.   Employee employee = employeeService.getEmployeeWithUserName(username);
    15.   System.out.println(employee);
    16.   if (employee == null){
    17.   return null;
    18.   }
    19.   /*认证*/
    20.   /*参数: 主体,正确的密码,盐,当前realm名称*/
    21.   SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
    22.   employee,
    23.   employee.getPassword(),
    24.   ByteSource.Util.bytes(employee.getUsername()),
    25.   this.getName());
    26.    
    27.   return info;
    28.   }
    29.    
    30.   /*授权
    31.   web doGetAuthorizationInfo 什么时候调用
    32.   1.发现访问路径对应的方法上面 有授权注解 就会调用doGetAuthorizationInfo
    33.   2.页面当中有授权标签 也会调用doGetAuthorizationInfo
    34.   * */
    35.   @Override
    36.   protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    37.   System.out.println("授权调用-------------------");
    38.   /*获取用户的身份信息*/
    39.   Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
    40.   /*根据当前用,查询角色和权限*/
    41.   List<String> roles = new ArrayList<>();
    42.   List<String> permissions = new ArrayList<>();
    43.    
    44.   /*判断当前用户是不是管理员 如果是管理员 拥有所有的权限*/
    45.   if(employee.getAdmin()){
    46.   /*拥有所有的权限*/
    47.   permissions.add("*:*");
    48.   }else {
    49.   /*查询角色*/
    50.   roles = employeeService.getRolesById(employee.getId());
    51.   /*查询权限*/
    52.   permissions = employeeService.getPermissionById(employee.getId());
    53.   }
    54.    
    55.   /*给授权信息*/
    56.   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    57.   info.addRoles(roles);
    58.   info.addStringPermissions(permissions);
    59.   return info;
    60.   }
    61.   }

    ? 4.配置realm数据源(在application-shiro.xml中配置)
    ?

    1.   <?xml version="1.0" encoding="UTF-8"?>
    2.   <beans xmlns="http://www.springframework.org/schema/beans"
    3.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4.   xmlns:context="http://www.springframework.org/schema/context"
    5.   xmlns:aop="http://www.springframework.org/schema/aop"
    6.   xmlns:tx="http://www.springframework.org/schema/tx"
    7.   xsi:schemaLocation="http://www.springframework.org/schema/beans
    8.   http://www.springframework.org/schema/beans/spring-beans.xsd
    9.   http://www.springframework.org/schema/context
    10.   http://www.springframework.org/schema/context/spring-context.xsd
    11.   http://www.springframework.org/schema/aop
    12.   http://www.springframework.org/schema/aop/spring-aop.xsd
    13.   http://www.springframework.org/schema/tx
    14.   http://www.springframework.org/schema/tx/spring-tx.xsd
    15.   ">
    16.    
    17.   <bean id="myFormFilter" class="com.itlike.web.filter.MyFormFilter"/>
    18.    
    19.    
    20.  
    21.   <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    22.  
    23.   <property name="loginUrl" value="/login"/>
    24.    
    25.  
    26.   <property name="filters">
    27.   <map>
    28.   <entry key="authc" value-ref="myFormFilter"/>
    29.   map>
    30.   property>
    31.    
    32.  
    33.   <property name="securityManager" ref="securityManager">property>
    34.  
    35.   <property name="filterChainDefinitions">
    36.   <value>
    37.   /static/** = anon
    38.   /login.jsp = anon
    39.   /logout = logout
    40.   /**=authc
    41.   value>
    42.   property>
    43.   bean>
    44.    
    45.  
    46.   <bean id="employeeRealm" class="com.itlike.web.realm.EmployeeRealm">
    47.   <property name="credentialsMatcher" ref="credentialsMatcher"/>
    48.   bean>
    49.    
    50.  
    51.   <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    52.  
    53.   <property name="hashAlgorithmName" value="md5"/>
    54.  
    55.   <property name="hashIterations" value="2">property>
    56.   bean>
    57.    
    58.  
    59.   <bean id="ehCache" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    60.   <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
    61.   bean>
    62.    
    63.    
    64.  
    65.   <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    66.  
    67.   <property name="realm" ref="employeeRealm"/>
    68.  
    69.   <property name="cacheManager" ref="ehCache"/>
    70.   bean>
    71.    
    72.  
    73.   <aop:config proxy-target-class="true" >aop:config>
    74.    
    75.  
    76.   <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor ">
    77.   <property name="securityManager" ref="securityManager">property>
    78.   bean>
    79.    
    80.   beans>

    ?
    ? 5.创建表单认证过滤器

    1.   public class MyFormFilter extends FormAuthenticationFilter {
    2.    
    3.   /*当认证成功时,会调用*/
    4.   protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
    5.   /*响应给浏览器*/
    6.   response.setCharacterEncoding("utf-8");
    7.   System.out.println("认证成功");
    8.   AjaxRes ajaxRes = new AjaxRes();
    9.   ajaxRes.setSuccess(true);
    10.   ajaxRes.setMsg("登录成功");
    11.   /*把对象转成json格式字符串*/
    12.   String jsonString = new ObjectMapper().writeValueAsString(ajaxRes);
    13.    
    14.   response.getWriter().print(jsonString);
    15.    
    16.   return false;
    17.   }
    18.    
    19.   /*当认证失败时, 会调用*/
    20.   protected boolean onLoginFailure(AuthenticationToken token,
    21.   AuthenticationException e,
    22.   ServletRequest request,
    23.   ServletResponse response) {
    24.   System.out.println("认证失败");
    25.    
    26.   AjaxRes ajaxRes = new AjaxRes();
    27.   ajaxRes.setSuccess(false);
    28.   if (e!=null){
    29.   /*获取异常名称*/
    30.   String name = e.getClass().getName();
    31.   if(name.equals(UnknownAccountException.class.getName())){
    32.   /*没有帐号*/
    33.   ajaxRes.setMsg("帐号不正确");
    34.   } else if(name.equals(IncorrectCredentialsException.class.getName())){
    35.   /*密码错误*/
    36.   ajaxRes.setMsg("密码不正确");
    37.   }else {
    38.   /*未知异常*/
    39.   ajaxRes.setMsg("未知错误");
    40.   }
    41.   }
    42.    
    43.   try {
    44.   /*把对象转成json格式字符串*/
    45.   String jsonString = new ObjectMapper().writeValueAsString(ajaxRes);
    46.   response.setCharacterEncoding("utf-8");
    47.   response.getWriter().print(jsonString);
    48.   } catch (IOException e1) {
    49.   e1.printStackTrace();
    50.   }
    51.    
    52.   /*响应给浏览器*/
    53.   return false;
    54.   }
    55.   }

    ? 登录授权

    • 当我们在控制器方法写了 @RequiresPermissions,Shiro在访问时, 就会判断有没有该权限

    • 如果没有,就不会执行对应方法
      实现过程
      1.在配置文件当中添加Shiro注解扫描
      ?

      1.  
      2.   <aop:config proxy-target-class="true" >aop:config>
      3.    
      4.  
      5.   <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor ">
      6.   <property name="securityManager" ref="securityManager">property>
      7.   bean>

      ? 2.在realm中添加授权信息

    1.   public class EmployeeRealm extends AuthorizingRealm {
    2.    
    3.   @Autowired
    4.   private EmployeeService employeeService;
    5.    
    6.   /*认证*/
    7.   @Override
    8.   protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    9.   System.out.println("来到了认证-------");
    10.   /*获取身份信息*/
    11.   String username = (String)token.getPrincipal();
    12.   System.out.println(username);
    13.   /*根据用户名当中查询有没有当前用户*/
    14.   Employee employee = employeeService.getEmployeeWithUserName(username);
    15.   System.out.println(employee);
    16.   if (employee == null){
    17.   return null;
    18.   }
    19.   /*认证*/
    20.   /*参数: 主体,正确的密码,盐,当前realm名称*/
    21.   SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
    22.   employee,
    23.   employee.getPassword(),
    24.   ByteSource.Util.bytes(employee.getUsername()),
    25.   this.getName());
    26.    
    27.   return info;
    28.   }
    29.   /*授权
    30.   web doGetAuthorizationInfo 什么时候调用
    31.   1.发现访问路径对应的方法上面 有授权注解 就会调用doGetAuthorizationInfo
    32.   2.页面当中有授权标签 也会调用doGetAuthorizationInfo
    33.   * */
    34.   @Override
    35.   protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    36.   System.out.println("授权调用-------------------");
    37.   /*获取用户的身份信息*/
    38.   Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
    39.   /*根据当前用,查询角色和权限*/
    40.   List<String> roles = new ArrayList<>();
    41.   List<String> permissions = new ArrayList<>();
    42.    
    43.   /*判断当前用户是不是管理员 如果是管理员 拥有所有的权限*/
    44.   if(employee.getAdmin()){
    45.   /*拥有所有的权限*/
    46.   permissions.add("*:*");
    47.   }else {
    48.   /*查询角色*/
    49.   roles = employeeService.getRolesById(employee.getId());
    50.   /*查询权限*/
    51.   permissions = employeeService.getPermissionById(employee.getId());
    52.   }
    53.    
    54.   /*给授权信息*/
    55.   SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    56.   info.addRoles(roles);
    57.   info.addStringPermissions(permissions);
    58.   return info;
    59.   }
    60.   }

    没有权限结果处理

    1.   @ExceptionHandler(AuthorizationException.class)
    2.   public void handleShiroException(HandlerMethod method,HttpServletResponse response) throws Exception{ /*method 发生异常的方法*/
    3.   /*跳转到一个界面 界面提示没有 权限*/
    4.   /*判断 当前的请求是不是Json请求 如果是 返回json给浏览器 让它自己来做跳转*/
    5.   /*获取方法上的注解*/
    6.   ResponseBody methodAnnotation = method.getMethodAnnotation(ResponseBody.class);
    7.   if (methodAnnotation != null){
    8.   //Ajax
    9.   AjaxRes ajaxRes = new AjaxRes();
    10.   ajaxRes.setSuccess(false);
    11.   ajaxRes.setMsg("你没有权限操作");
    12.   String s = new ObjectMapper().writeValueAsString(ajaxRes);
    13.   response.setCharacterEncoding("utf-8");
    14.   response.getWriter().print(s);
    15.   }else {
    16.   response.sendRedirect("nopermission.jsp");
    17.   }
    18.   }

    权限按钮控制

    • 引入Shiro的标签库
    • 在需要权限控制的地方添加对应的shiro标签
    1.   <%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
    2.   <shiro:hasPermission name="employee:add">
    3.   <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" id="add">添加a>
    4.   shiro:hasPermission>

    密码散列

    在保存用户时, 给用户密码进行加密处理

    1.   /*把密码进行加密*/
    2.   把用户名作为盐值,进行2次散列
    3.   Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getUsername(), 2);
    4.   employee.setPassword(md5Hash.toString());

    在认证当中添加密码处理

    1.   /*认证*/
    2.   /*参数: 主体,正确的密码,盐,当前realm名称*/
    3.   SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
    4.   employee,
    5.   employee.getPassword(),
    6.   ByteSource.Util.bytes(employee.getUsername()),
    7.   this.getName());

    添加凭证匹配器

    1.  
    2.   <bean id="employeeRealm" class="com.itlike.realm.EmployeeRealm">
    3.   <property name="credentialsMatcher" ref="credentialsMatcher"/>
    4.   bean>
    5.    
    6.  
    7.   <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    8.  
    9.   <property name="hashAlgorithmName" value="md5"/>
    10.  
    11.   <property name="hashIterations" value="2">property>
    12.   bean>

    权限缓存

    • 进入页面时, 页面当中写了Shiro的标签,每一个标签都要去到授权当中进行一次授权查询
    • 授权查询只使用一次即可, 所以使用缓存,把对应的内容缓存起来,下次再去, 直接从缓存当中进行查询

    使用步骤:

    ? 1.添加缓存pom依赖
    1.   <dependency>
    2.   <groupId>org.apache.shirogroupId>
    3.   <artifactId>shiro-ehcacheartifactId>
    4.   <version>1.2.2version>
    5.   dependency>
    2.添加shiro缓存配置

    ? 添加shiro-ehcache.xml
    ?

    1.   <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2.   xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
    3.   <defaultCache
    4.   maxElementsInMemory="1000"
    5.   maxElementsOnDisk="10000000"
    6.   eternal="false"
    7.   overflowToDisk="false"
    8.   diskPersistent="false"
    9.   timeToIdleSeconds="120"
    10.   timeToLiveSeconds="120"
    11.   diskExpiryThreadIntervalSeconds="120"
    12.   memoryStoreEvictionPolicy="LRU">
    13.   defaultCache>
    14.   ehcache>

    ? 配置约束

    3.application-shiro中配置缓存管理器

    ?

    1.  
    2.   <bean id="ehCache" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    3.   <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
    4.   bean>
    4.把缓存管理器添加到安全管理器当中
    1.  
    2.   <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    3.   <property name="realm" ref="employeeRealm" />
    4.   <property name="cacheManager" ref="ehCache"/>
    5.   bean>

    菜单权限管理

    菜单页面

    页面搭建

    1.创建菜单表
    1.   CREATE TABLE `menu` (
    2.   `id` bigint(20) NOT NULL,
    3.   `text` varchar(10) DEFAULT NULL,
    4.   `url` varchar(30) DEFAULT NULL,
    5.   `parent_id` bigint(20) DEFAULT NULL,
    6.   PRIMARY KEY (`id`),
    7.   KEY `parent_id` (`parent_id`),
    8.   CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `menu` (`id`)
    9.   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    2.生成Mapper,添加父菜单字段
    1.   @Setter@Getter@ToString
    2.   public class Menu {
    3.   private Long id;
    4.   private String text;
    5.   private String url;
    6.   private Menu parent;
    7.   private Permission permission;
    8.   private List<Menu> children = new ArrayList<>();
    9.   }
    3.创建Menu页面
    1.  
    2.   <table id="menu_datagrid">
    3.   <thead>
    4.   <tr>
    5.   <th>名称th>
    6.   <th>urlth>
    7.   <th>父菜单th>
    8.   tr>
    9.   thead>
    10.   table>
    11.    
    12.  
    13.   <div id="menu_toolbar">
    14.   <div>
    15.   <a class="easyui-linkbutton" iconCls="icon-add" plain="true" id="add">新增a>
    16.   <a class="easyui-linkbutton" iconCls="icon-edit" plain="true" id="edit">编辑a>
    17.   <a class="easyui-linkbutton" iconCls="icon-remove" plain="true" id="del">刪除a>
    18.   <a class="easyui-linkbutton" iconCls="icon-reload" plain="true" id="reload">刷新a>
    19.   div>
    20.   div>
    21.    
    22.   <div id="menu_dialog">
    23.   <form id="menu_form" method="post">
    24.   <table align="center" style="margin-top: 15px;">
    25.   <input type="hidden" name="id">
    26.   <tr>
    27.   <td>名称td>
    28.   <td><input type="text" name="text">td>
    29.   tr>
    30.   <tr>
    31.   <td>urltd>
    32.   <td><input type="text" name="url">td>
    33.   tr>
    34.   <tr>
    35.   <td>父菜单td>
    36.   <td><input type="text" id="parentMenu" name="parent.id" class="easyui-combobox" placeholder="请选择父菜单"/>td>
    37.   tr>
    38.   table>
    39.   form>
    40.   div>
    41.    
    42.  
    43.   <div id="menu_dialog_bt">
    44.   <a class="easyui-linkbutton" iconCls="icon-save" plain="true" id="save">保存a>
    45.   <a class="easyui-linkbutton" iconCls="icon-cancel" plain="true" id="cancel">取消a>
    46.   div>
    4.创建Menu.js
    1.   $(function () {
    2.    
    3.   $("#menu_datagrid").datagrid({
    4.   url:"/menuList",
    5.   columns:[[
    6.   {field:'text',title:'名称',width:1,align:'center'},
    7.   {field:'url',title:'跳转地址',width:1,align:'center'},
    8.   {field:'parent',title:'父菜单',width:1,align:'center',formatter:function(value,row,index){
    9.   return value?value.text:'';
    10.   }
    11.   }
    12.   ]],
    13.   fit:true,
    14.   rownumbers:true,
    15.   singleSelect:true,
    16.   striped:true,
    17.   pagination:true,
    18.   fitColumns:true,
    19.   toolbar:'#menu_toolbar'
    20.   });
    21.    
    22.   /*
    23.   * 初始化新增/编辑对话框
    24.   */
    25.   $("#menu_dialog").dialog({
    26.   width:300,
    27.   height:240,
    28.   closed:true,
    29.   buttons:'#menu_dialog_bt'
    30.   });
    31.   /*加载选择父菜单*/
    32.   $("#parentMenu").combobox({
    33.   width:150,
    34.   panelHeight:'auto',
    35.   editable:false,
    36.   url:'parentList',
    37.   textField:'text',
    38.   valueField:'id',
    39.   onLoadSuccess:function () { /*数据加载完毕之后回调*/
    40.   $("#parentMenu").each(function(i){
    41.   var span = $(this).siblings("span")[i];
    42.   var targetInput = $(span).find("input:first");
    43.   if(targetInput){
    44.   $(targetInput).attr("placeholder", $(this).attr("placeholder"));
    45.   }
    46.   });
    47.   }
    48.   });
    49.   /*添加菜单*/
    50.   $("#add").click(function () {
    51.   $("#menu_dialog").dialog("setTitle","添加菜单");
    52.   $("#menu_form").form("clear");
    53.   $("#menu_dialog").dialog("open");
    54.   });
    55.   /*保存菜单*/
    56.   $("#save").click(function () {
    57.   /*判断当前是添加 还是编辑*/
    58.   var id = $("[name='id']").val();
    59.   var url;
    60.   if(id){
    61.   var parent_id = $("[name='parent.id']").val();
    62.   if (id == parent_id) {
    63.   $.messager.alert("温馨提示","不能设置自己为父菜单");
    64.   return;
    65.   }
    66.   /*编辑*/
    67.   url = "updateMenu";
    68.   }else {
    69.   /*添加*/
    70.   url= "saveMenu";
    71.   }
    72.    
    73.   /*提交表单*/
    74.   $("#menu_form").form("submit",{
    75.   url:url,
    76.   success:function (data) {
    77.   data = $.parseJSON(data);
    78.   if (data.success){
    79.   $.messager.alert("温馨提示",data.msg);
    80.   /*关闭对话框 */
    81.   $("#menu_dialog").dialog("close");
    82.   $("#parentMenu").combobox("reload");
    83.   $("#menu_datagrid").datagrid("reload");
    84.   } else {
    85.   $.messager.alert("温馨提示",data.msg);
    86.   }
    87.   }
    88.   });
    89.   });
    90.   /*编辑菜单*/
    91.   $("#edit").click(function () {
    92.    
    93.   $("#menu_form").form("clear");
    94.   /*获取当前选中的行*/
    95.   var rowData = $("#menu_datagrid").datagrid("getSelected");
    96.   if(!rowData){
    97.   $.messager.alert("提示","选择一行数据进行编辑");
    98.   return;
    99.   }
    100.   /*父菜单回显*/
    101.   if(rowData.parent){
    102.   rowData["parent.id"] = rowData.parent.id;
    103.   }else {/*回显的placeholder*/
    104.   $("#parentMenu").each(function(i){
    105.   var span = $(this).siblings("span")[i];
    106.   var targetInput = $(span).find("input:first");
    107.   if(targetInput){
    108.   $(targetInput).attr("placeholder", $(this).attr("placeholder"));
    109.   }
    110.   });
    111.   }
    112.   /*弹出对话框*/
    113.   $("#menu_dialog").dialog("setTitle","编辑菜单");
    114.   $("#menu_dialog").dialog("open");
    115.   /*选中数据的回示*/
    116.   $("#menu_form").form("load",rowData);
    117.   });
    118.    
    119.   $("#cancel").click(function () {
    120.   $("#menu_dialog").dialog("close");
    121.   });
    122.    
    123.   $("#del").click(function () {
    124.   /*获取当前选中的行*/
    125.   var rowData = $("#menu_datagrid").datagrid("getSelected");
    126.   if(!rowData){
    127.   $.messager.alert("提示","选择一行数据进行删除");
    128.   return;
    129.   }
    130.   /*提醒用户,是否做删除操作*/
    131.   $.messager.confirm("确认","是否做删除操作",function (res) {
    132.   if(res){
    133.   /*做离职操作*/
    134.   $.get("/deleteMenu?id="+rowData.id,function (data) {
    135.   if (data.success){
    136.   $.messager.alert("温馨提示",data.msg);
    137.   /*重新加载下拉列表数据*/
    138.   $("#parentMenu").combobox("reload");
    139.   /*重新加载数据表格*/
    140.   $("#menu_datagrid").datagrid("reload");
    141.   } else {
    142.   $.messager.alert("温馨提示",data.msg);
    143.   }
    144.    
    145.   });
    146.   }
    147.   });
    148.   });
    149.    
    150.   });

    菜单列表

    1.接收菜单请求
    1.   @Service
    2.   public class MenuServiceImpl implements MenuService {
    3.    
    4.   @Autowired
    5.   private MenuMapper menuMapper;
    6.    
    7.   @Override
    8.   public PageListRes getMenuList(QueryVo vo) {
    9.   /*调用mapper 查询菜单 */
    10.   Page<Object> page = PageHelper.startPage(vo.getPage(), vo.getRows());
    11.   List<Menu> menus = menuMapper.selectAll();
    12.   /*封装成pageList*/
    13.   PageListRes pageListRes = new PageListRes();
    14.   pageListRes.setTotal(page.getTotal());
    15.   pageListRes.setRows(menus);
    16.   return pageListRes;
    17.   }
    18.    
    19.   }
    2.底层实现
    1.   <resultMap id="BaseResultMap" type="com.itlike.domain.Menu" >
    2.   <id column="id" property="id" jdbcType="BIGINT" />
    3.   <result column="text" property="text" jdbcType="VARCHAR" />
    4.   <result column="url" property="url" jdbcType="VARCHAR" />
    5.    
    6.   <association property="parent" javaType="com.itlike.domain.Menu" columnPrefix="m_">
    7.   <result property="id" column="id"/>
    8.   <result property="text" column="text"/>
    9.   <result property="url" column="url"/>
    10.   association>
    11.    
    12.   <association property="permission" javaType="com.itlike.domain.Permission">
    13.   <result property="pid" column="pid"/>
    14.   <result property="pname" column="pname"/>
    15.   <result property="presource" column="presource"/>
    16.   association>
    17.    
    18.   <collection property="children" ofType="com.itlike.domain.Menu" select="listChildMenu" column="id"/>
    19.    
    20.   resultMap>
    21.  
    22.   <select id="selectAll" resultMap="BaseResultMap" >
    23.   SELECT
    24.   m1.id,
    25.   m1.text,
    26.   m1.url,
    27.   m2.id as m_id,
    28.   m2.text as m_text,
    29.   m2.url as m_url
    30.   from menu as m1
    31.   LEFT JOIN menu as m2
    32.   ON m1.parent_id = m2.id
    33.   order by m1.id desc
    34.   select>
    3.页面处理
    1.   formatter这个属性属于列参数,意思就是对当前列的数据进行格式化操作,它是一个函数,有三个参数,value,row,index,
    2.   value:代表当前单元格中的值,
    3.   row:代表当前行,
    4.   index:代表当前行的下标,
    5.   可以使用return 返回你想要的数据显示在单元格中;
    6.   formatter:function(value,row,index){
    7.   return value?value.text:'';
    8.   }

    菜单添加

    获取所有父菜单

    1.  
    2.   <td>父菜单td>
    3.   <td><input type="text" id="parentMenu" name="parent.id" class="easyui-combobox" placeholder="请选择父菜单"/>td>
    4.  
    5.    
    6.   $(function () {
    7.   /*加载选择父菜单*/
    8.   $("#parentMenu").combobox({
    9.   width:150,
    10.   panelHeight:'auto',
    11.   editable:false,
    12.   url:'parentList',
    13.   textField:'text',
    14.   valueField:'id',
    15.   onLoadSuccess:function () { /*数据加载完毕之后回调*/
    16.   $("#parentMenu").each(function(i){
    17.   var span = $(this).siblings("span")[i];
    18.   var targetInput = $(span).find("input:first");
    19.   if(targetInput){
    20.   $(targetInput).attr("placeholder", $(this).attr("placeholder"));
    21.   }
    22.   });
    23.   }
    24.   });
    25.   });

    保存菜单

    监听保存点击
    1.   /*保存菜单*/
    2.   $("#save").click(function () {
    3.   /*判断当前是添加 还是编辑*/
    4.   var id = $("[name='id']").val();
    5.   var url;
    6.   if(id){
    7.   var parent_id = $("[name='parent.id']").val();
    8.   if (id == parent_id) {
    9.   $.messager.alert("温馨提示","不能设置自己为父菜单");
    10.   return;
    11.   }
    12.   /*编辑*/
    13.   url = "updateMenu";
    14.   }else {
    15.   /*添加*/
    16.   url= "saveMenu";
    17.   }
    18.    
    19.   /*提交表单*/
    20.   $("#menu_form").form("submit",{
    21.   url:url,
    22.   success:function (data) {
    23.   data = $.parseJSON(data);
    24.   if (data.success){
    25.   $.messager.alert("温馨提示",data.msg);
    26.   /*关闭对话框 */
    27.   $("#menu_dialog").dialog("close");
    28.   $("#parentMenu").combobox("reload");
    29.   $("#menu_datagrid").datagrid("reload");
    30.   } else {
    31.   $.messager.alert("温馨提示",data.msg);
    32.   }
    33.   }
    34.   });
    35.   });
    业务处理
    1.   /*保存菜单*/
    2.   @RequestMapping("/saveMenu")
    3.   @ResponseBody
    4.   public AjaxRes saveMenu(Menu menu){
    5.   AjaxRes ajaxRes = new AjaxRes();
    6.   try {
    7.   /*调用业务层,保存菜单*/
    8.   menuService.saveMenu(menu);
    9.   ajaxRes.setMsg("保存成功");
    10.   ajaxRes.setSuccess(true);
    11.   }catch (Exception e){
    12.   ajaxRes.setSuccess(false);
    13.   ajaxRes.setMsg("保存失败");
    14.   System.out.println(e);
    15.   }
    16.   return ajaxRes;
    17.   }

    编辑菜单

    1.   /*编辑菜单*/
    2.   $("#edit").click(function () {
    3.    
    4.   $("#menu_form").form("clear");
    5.   /*获取当前选中的行*/
    6.   var rowData = $("#menu_datagrid").datagrid("getSelected");
    7.   if(!rowData){
    8.   $.messager.alert("提示","选择一行数据进行编辑");
    9.   return;
    10.   }
    11.   /*父菜单回显*/
    12.   if(rowData.parent){
    13.   rowData["parent.id"] = rowData.parent.id;
    14.   }else {/*回显的placeholder*/
    15.   $("#parentMenu").each(function(i){
    16.   var span = $(this).siblings("span")[i];
    17.   var targetInput = $(span).find("input:first");
    18.   if(targetInput){
    19.   $(targetInput).attr("placeholder", $(this).attr("placeholder"));
    20.   }
    21.   });
    22.   }
    23.   /*弹出对话框*/
    24.   $("#menu_dialog").dialog("setTitle","编辑菜单");
    25.   $("#menu_dialog").dialog("open");
    26.   /*选中数据的回示*/
    27.   $("#menu_form").form("load",rowData);
    28.   });

    删除菜单

    监听删除按钮
    1.   $("#del").click(function () {
    2.   /*获取当前选中的行*/
    3.   var rowData = $("#menu_datagrid").datagrid("getSelected");
    4.   if(!rowData){
    5.   $.messager.alert("提示","选择一行数据进行删除");
    6.   return;
    7.   }
    8.   /*提醒用户,是否做删除操作*/
    9.   $.messager.confirm("确认","是否做删除操作",function (res) {
    10.   if(res){
    11.   /*做离职操作*/
    12.   $.get("/deleteMenu?id="+rowData.id,function (data) {
    13.   if (data.success){
    14.   $.messager.alert("温馨提示",data.msg);
    15.   /*重新加载下拉列表数据*/
    16.   $("#parentMenu").combobox("reload");
    17.   /*重新加载数据表格*/
    18.   $("#menu_datagrid").datagrid("reload");
    19.   } else {
    20.   $.messager.alert("温馨提示",data.msg);
    21.   }
    22.    
    23.   });
    24.   }
    25.   });
    26.   });
    处理业务逻辑
    1.   @Override
    2.   public AjaxRes deleteMenu(Long id) {
    3.    
    4.   AjaxRes ajaxRes = new AjaxRes();
    5.   try {
    6.   /*1.打破菜单关系*/
    7.   menuMapper.updateMenuRel(id);
    8.   /*2.删除记录*/
    9.   menuMapper.deleteByPrimaryKey(id);
    10.   ajaxRes.setMsg("删除成功");
    11.   ajaxRes.setSuccess(true);
    12.   }catch (Exception e){
    13.   ajaxRes.setSuccess(false);
    14.   ajaxRes.setMsg("删除失败");
    15.   System.out.println(e);
    16.   }
    17.   return ajaxRes;
    18.   }
    1.  
    2.   <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    3.   delete from menu
    4.   where id = #{id,jdbcType=BIGINT}
    5.   delete>
    6.    
    7.  
    8.   <update id="updateByPrimaryKey" parameterType="com.itlike.domain.Menu" >
    9.   update menu
    10.   set text = #{text},
    11.   url = #{url},
    12.   parent_id = #{parent.id}
    13.   where id = #{id}
    14.   update>

    菜单权限

    1.   在**menu**数据表中, 添加外键, 每一个菜单对应一个权限,通过判断用户有没有该权限来控制菜单的显示隐藏
    2.   设置菜单对应权限并取出

    1.在menu表中添加权限外键

    2.在菜单domain当中添加权限对象

    tree数据加载

    1.   $(function () {
    2.   $("#tabs").tabs({
    3.   fit:true
    4.   })
    5.   $('#tree').tree({
    6.   url:"/getTreeData",
    7.   lines:true,
    8.   onSelect: function(node){
    9.   /*在添加之前, 做判断 判断这个标签是否存在 */
    10.   var exists = $("#tabs").tabs("exists",node.text);
    11.   if(exists){
    12.   /*存在,就让它选中*/
    13.   $("#tabs").tabs("select",node.text);
    14.   }else {
    15.   if (node.url !=''&& node.url !=null){
    16.   /*如果不存在 ,添加新标签*/
    17.   $("#tabs").tabs("add",{
    18.   title:node.text,
    19.   /*href:node.attributes.url,*/ /*href 引入的是body当中*/
    20.   content:"",
    21.   closable:true
    22.   })
    23.   }
    24.   }
    25.   },
    26.   onLoadSuccess: function (node, data) {
    27.   console.log(data[0].children[0].id);
    28.   if (data.length > 0) {
    29.   //找到第一个元素
    30.   var n = $('#tree').tree('find', data[0].children[0].id);
    31.   //调用选中事件
    32.   $('#tree').tree('select', n.target);
    33.   }
    34.   }
    35.   });
    36.   });

    3.查询菜单时, 把对应权限查出来, 检查权限

    1.   @Override
    2.   public List getTreeData() {
    3.   List treeData = menuMapper.getTreeData();
    4.   /*
    5.   判断当前用户有没有对应的权限
    6.   如果没有就从集合当中移除
    7.   */
    8.   /*获取用户 判断用户是否是管理员 是管理就不需要做判断*/
    9.   Subject subject = SecurityUtils.getSubject();
    10.   /*当前的用户*/
    11.   Employee employee = (Employee)subject.getPrincipal();
    12.   if (!employee.getAdmin()){
    13.   /*做检验权限*/
    14.   checkPermission(treeData);
    15.   }
    16.   return treeData;
    17.   }
    18.    
    19.   public void checkPermission(List menus){
    20.   //获取主体
    21.   Subject subject = SecurityUtils.getSubject();
    22.   //遍历所有的菜单及子菜单
    23.   Iterator iterator = menus.iterator();
    24.   while (iterator.hasNext()){
    25.   Menu menu = iterator.next();
    26.   if (menu.getPermission() !=null){
    27.   //判断当前menu是否有权限对象,如果说没有 当前遍历的菜单从集合当中移除
    28.   String presource = menu.getPermission().getPresource();
    29.   if (!subject.isPermitted(presource)){
    30.   //当前遍历的菜单从集合当中移除
    31.   iterator.remove();
    32.   continue;
    33.   }
    34.   }
    35.   /*判断是否有子菜单 有子菜单也要做权限检验*/
    36.   if (menu.getChildren().size() > 0){
    37.   checkPermission(menu.getChildren());
    38.   }
    39.   }
    40.   }
    1.   <resultMap id="BaseResultMap" type="com.itlike.domain.Menu" >
    2.   <id column="id" property="id" jdbcType="BIGINT" />
    3.   <result column="text" property="text" jdbcType="VARCHAR" />
    4.   <result column="url" property="url" jdbcType="VARCHAR" />
    5.    
    6.   <association property="parent" javaType="com.itlike.domain.Menu" columnPrefix="m_">
    7.   <result property="id" column="id"/>
    8.   <result property="text" column="text"/>
    9.   <result property="url" column="url"/>
    10.   association>
    11.    
    12.   <association property="permission" javaType="com.itlike.domain.Permission">
    13.   <result property="pid" column="pid"/>
    14.   <result property="pname" column="pname"/>
    15.   <result property="presource" column="presource"/>
    16.   association>
    17.    
    18.   <collection property="children" ofType="com.itlike.domain.Menu" select="listChildMenu" column="id"/>
    19.    
    20.   resultMap>
    21.    
    22.  
    23.   <select id="getTreeData" resultMap="BaseResultMap">
    24.   select * from menu as m
    25.   LEFT JOIN permission as p
    26.   on m.permission_id = p.pid where parent_id is null
    27.   select>
    28.    
    29.  
    30.   <select id="listChildMenu" resultMap="BaseResultMap">
    31.   select * from menu as m
    32.   LEFT JOIN permission as p
    33.   on m.permission_id = p.pid where parent_id = #{id}
    34.   select>

    系统日志

    建立日志表和对应mapper

    1.   CREATE TABLE `systemlog` (
    2.   `id` bigint(20) NOT NULL AUTO_INCREMENT,
    3.   `optime` datetime DEFAULT NULL,
    4.   `ip` varchar(20) DEFAULT NULL,
    5.   `function` varchar(255) DEFAULT NULL,
    6.   `params` varchar(255) DEFAULT NULL,
    7.   PRIMARY KEY (`id`)
    8.   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    添加拦截器,记录当前请求的ip

    创建本地线程变量

    1.   public class RequestUtil {
    2.   public static ThreadLocal local = new ThreadLocal();
    3.    
    4.   public static HttpServletRequest getRequest(){
    5.   return local.get();
    6.   }
    7.    
    8.   public static void setRequest(HttpServletRequest request){
    9.   local.set(request);
    10.   }
    11.   }

    配置拦截器拦截所有请求

    1.  
    2.   <mvc:interceptors>
    3.   <mvc:interceptor>
    4.   <mvc:mapping path="/*"/>
    5.   <bean class="com.itlike.interceptor.RequestInterceptor">bean>
    6.   mvc:interceptor>
    7.   mvc:interceptors>

    创建拦截器把当前请求写入到本地线程变量

    1.   public class RequestInterceptor implements HandlerInterceptor {
    2.   @Override
    3.   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    4.   throws Exception {
    5.   System.out.println("来到了拦截器...");
    6.   RequestUtil.setRequest(request);
    7.   return true;
    8.   }
    9.   }

     

    1.   Systemlog systemlog = new Systemlog();
    2.   //设置ip地址 request 添加拦截器 获取请求对象
    3.   HttpServletRequest request = RequestUtil.getRequest();
    4.   if (request != null){
    5.   String IP = request.getRemoteAddr();
    6.   System.out.println(IP);
    7.   systemlog.setIp(IP);
    8.   }

    创建日志切面、在切面中获取ip、获取当前执行的方法及参数

    1.   public class SystemAspect {
    2.   @Autowired
    3.   private SystemlogMapper systemlogMapper;
    4.    
    5.   public void writeLog(JoinPoint joinPoint) throws JsonProcessingException {
    6.   System.out.println("记录日志");
    7.   //设置时间
    8.   Systemlog systemlog = new Systemlog();
    9.   systemlog.setOptime(new Date());
    10.   //设置ip地址 request 添加拦截器 获取请求对象
    11.   HttpServletRequest request = RequestUtil.getRequest();
    12.   if (request != null){
    13.   String IP = request.getRemoteAddr();
    14.   System.out.println(IP);
    15.   systemlog.setIp(IP);
    16.   }
    17.   //方法
    18.   //获取目标执行方法的全路径
    19.   String name = joinPoint.getTarget().getClass().getName();
    20.   //获取方法名称
    21.   String signature = joinPoint.getSignature().getName();
    22.   String func = name+":"+signature;
    23.   systemlog.setFunction(func);
    24.    
    25.   //获取方法参数
    26.   String params = new ObjectMapper().writeValueAsString(joinPoint.getArgs());
    27.   systemlog.setParams(params);
    28.   systemlogMapper.insert(systemlog);
    29.   }
    30.   }

    添加切面

    1.  
    2.   <bean id="SystemAspect" class="com.itlike.aspect.SystemAspect">bean>
    3.    
    4.   <aop:config>
    5.   <aop:pointcut expression="execution(* com.itlike.service.*.*(..))" id="servicePoint" />
    6.   <aop:aspect ref="SystemAspect">
    7.   <aop:after method="writeLog" pointcut-ref="servicePoint"/>
    8.   aop:aspect>
    9.   aop:config>

    Excel导入导出

    介绍

    1.   操作Excel的方式jxl和poi
    2.   官方文档
    3.   https://poi.apache.org/components/spreadsheet/quick-guide.html#CellContents
    4.   参考文档
    5.   https://www.cnblogs.com/huajiezh/p/5467821.html
    6.   依赖
    7.  
    8.   <groupId>org.apache.poigroupId>
    9.   <artifactId>poiartifactId>
    10.   <version>4.0.1version>
    11.  

    导出

    1.   // Excel导出
    2.   $("#excelOut").click(function () {
    3.   window.open('/downloadExcel')
    4.   });
    1.   @RequestMapping("/downloadExcel")
    2.   @ResponseBody
    3.   public void downloadExcel(HttpServletResponse response){
    4.   try {
    5.   System.out.println("---------downloadExcel---------");
    6.   //1.从数据库当中取列表数据
    7.   QueryVo queryVo = new QueryVo();
    8.   queryVo.setPage(1);
    9.   queryVo.setRows(10);
    10.   PageListRes plr = employeeService.getEmployee(queryVo);
    11.   List employees = (List)plr.getRows();
    12.   //2.创建Excel 写到excel当中
    13.   HSSFWorkbook wb = new HSSFWorkbook();
    14.   HSSFSheet sheet = wb.createSheet("员工数据");
    15.   //创建一行
    16.   HSSFRow row = sheet.createRow(0);
    17.   //设置行的每一列的数据
    18.   row.createCell(0).setCellValue("编号");
    19.   row.createCell(1).setCellValue("用户名");
    20.   row.createCell(2).setCellValue("入职日期");
    21.   row.createCell(3).setCellValue("电话");
    22.   row.createCell(4).setCellValue("邮件");
    23.    
    24.   HSSFRow employeeRow = null;
    25.   /*取出每一个员工来去设置数据*/
    26.   for(int i = 0; i < employees.size(); i++){
    27.   Employee employee = employees.get(i);
    28.   employeeRow = sheet.createRow(i+1);
    29.   employeeRow.createCell(0).setCellValue(employee.getId());
    30.   employeeRow.createCell(1).setCellValue(employee.getUsername());
    31.   if (employee.getInputtime() !=null){
    32.   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    33.   String format = sdf.format(employee.getInputtime());
    34.   employeeRow.createCell(2).setCellValue(format);
    35.   }else {
    36.   employeeRow.createCell(2).setCellValue("");
    37.   }
    38.   employeeRow.createCell(3).setCellValue(employee.getTel());
    39.   employeeRow.createCell(4).setCellValue(employee.getEmail());
    40.   }
    41.    
    42.   //3.响应给浏览器
    43.   String fileName = new String("员工数据.xls".getBytes("utf-8"), "iso8859-1");
    44.   response.setHeader("content-Disposition","attachment;filename="+fileName);
    45.   wb.write(response.getOutputStream());
    46.    
    47.   } catch (Exception e) {
    48.   e.printStackTrace();
    49.   }
    50.   }

    ?
    ?

    导入

    上传界面

    1.   <div id="excelUpload">
    2.   <form method="post" enctype="multipart/form-data">
    3.   <tabel>
    4.   <tr>
    5.   <td><input type="file" name="excel" style="width: 180px; margin-top: 20px; margin-left: 5px;">td>
    6.   <td><a href="javascript:void(0);" id="downloadTml">下载模板a>td>
    7.   tr>
    8.   tabel>
    9.   form>
    10.   div>
    1.   $("#excelUpload").dialog({
    2.   width:260,
    3.   height:180,
    4.   title:"导入Excel",
    5.   buttons:[{
    6.   text:'保存',
    7.   handler:function(){
    8.    
    9.   }
    10.   },{
    11.   text:'关闭',
    12.   handler:function(){
    13.   $("#excelUpload").dialog("close");
    14.   }
    15.   }],
    16.   closed:true
    17.   })
    18.    
    19.   $("#excelImpot").click(function () {
    20.   $("#excelUpload").dialog("open");
    21.   });

    下载模板

    1.   /*下载Excel模板*/
    2.   $("#downloadTml").click(function () {
    3.   window.open('/downloadExcelTpl')
    4.   });
    1.   /*下载模板*/
    2.   @RequestMapping("downloadExcelTpl")
    3.   @ResponseBody
    4.   public void downloadExcelTpl(HttpServletRequest request, HttpServletResponse response){
    5.   FileInputStream is = null;
    6.   try {
    7.   String fileName = new String("EmployeeTpl.xls".getBytes("utf-8"), "iso8859-1");
    8.   response.setHeader("content-Disposition","attachment;filename="+fileName);
    9.   /*获取文件路径*/
    10.   String realPath = request.getSession().getServletContext().getRealPath("static/ExcelTml.xls");
    11.   is = new FileInputStream(realPath);
    12.   IOUtils.copy(is,response.getOutputStream());
    13.   }catch (Exception e){
    14.   e.printStackTrace();
    15.   }finally {
    16.   if (is != null){
    17.   try {
    18.   is.close();
    19.   } catch (IOException e) {
    20.   e.printStackTrace();
    21.   }
    22.   }
    23.   }
    24.   }

    上传Excel处理

    上传模板

    1.   // 打开上传窗口
    2.   $("#excelIn").click(function () {
    3.   $("#excelUpload").dialog("open");
    4.   });
    5.    
    6.   // Excel导入
    7.   $("#excelUpload").dialog({
    8.   width:260,
    9.   height:180,
    10.   title:"导入Excel",
    11.   buttons:[{
    12.   text:'保存',
    13.   handler:function(){
    14.   $("#uploadForm").form("submit",{
    15.   url:"uploadExcelFile",
    16.   success:function (data) {
    17.   data = $.parseJSON(data);
    18.   if (data.success){
    19.   $.messager.alert("温馨提示",data.msg);
    20.   /*关闭对话框 */
    21.   $("#excelUpload").dialog("close");
    22.   /*重新加载数据表格*/
    23.   $("#dg").datagrid("reload");
    24.   } else {
    25.   $.messager.alert("温馨提示",data.msg);
    26.   }
    27.   }
    28.   })
    29.   }
    30.   },{
    31.   text:'关闭',
    32.   handler:function(){
    33.   $("#excelUpload").dialog("close");
    34.   }
    35.   }],
    36.   closed:true
    37.   });

    业务处理

    1.   /*配置文件上传解析器 mvc配置当中*/
    2.   @RequestMapping("/uploadExcelFile")
    3.   @ResponseBody
    4.   @RequiresPermissions("employee:add")
    5.   public AjaxRes uploadExcelFile(MultipartFile excel){
    6.   AjaxRes ajaxRes = new AjaxRes();
    7.   try {
    8.   ajaxRes.setMsg("导入成功");
    9.   ajaxRes.setSuccess(true);
    10.   HSSFWorkbook wb = new HSSFWorkbook(excel.getInputStream());
    11.   HSSFSheet sheet = wb.getSheetAt(0);
    12.   /*获取最大的行号*/
    13.   int lastRowNum = sheet.getLastRowNum();
    14.   Row employeeRow = null;
    15.   if(1 <= lastRowNum)
    16.   {
    17.   employeeRow = sheet.getRow(0);
    18.   if(!getCellValue(employeeRow.getCell(1)).toString().equals("用户名"))
    19.   throw new Exception("格式错误");
    20.   else if(!getCellValue(employeeRow.getCell(2)).toString().equals("入职日期"))
    21.   throw new Exception("格式错误");
    22.   else if(!getCellValue(employeeRow.getCell(3)).toString().equals("电话"))
    23.   throw new Exception("格式错误");
    24.   else if(!getCellValue(employeeRow.getCell(4)).toString().equals("邮件"))
    25.   throw new Exception("格式错误");
    26.   }
    27.   for (int i=1; i <= lastRowNum; i++){
    28.   employeeRow = sheet.getRow(i);
    29.   Employee employee = new Employee();
    30.   employee.setState(true);
    31.   employee.setUsername(getCellValue(employeeRow.getCell(1)).toString());
    32.    
    33.   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    34.   Date parse = sdf.parse(getCellValue(employeeRow.getCell(2)).toString());
    35.   employee.setInputtime(parse);
    36.   employee.setTel(getCellValue(employeeRow.getCell(3)).toString());
    37.   employee.setEmail(getCellValue(employeeRow.getCell(4)).toString());
    38.   employee.setPassword("123456");
    39.   employeeService.saveEmployee(employee);
    40.   }
    41.   }catch (Exception e){
    42.   e.printStackTrace();
    43.   ajaxRes.setMsg("导入失败!"+e.getMessage());
    44.   ajaxRes.setSuccess(false);
    45.   }
    46.   return ajaxRes;
    47.   }
    48.    
    49.   private Object getCellValue(Cell cell){
    50.   switch (cell.getCellType()) {
    51.   case STRING:
    52.   return cell.getRichStringCellValue().getString();
    53.   case NUMERIC:
    54.   if (DateUtil.isCellDateFormatted(cell)) {
    55.   return cell.getDateCellValue();
    56.   } else {
    57.   return cell.getNumericCellValue();
    58.   }
    59.   case BOOLEAN:
    60.   return cell.getBooleanCellValue();
    61.   case FORMULA:
    62.   return cell.getCellFormula();
    63.   }
    64.   return cell;
    65.   }

    配置文件上传解析器

    1.  
    2.   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    3.   <property name="maxUploadSize">
    4.   <value>1040000value>
    5.   property>
    6.   bean>