表格

 

一、表格样式:

JSP:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<title>培训讲师管理</title>

<link href="${ctx}/static/images/common/logoicond.ico" rel="Shortcut Icon">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/common/dialog.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/common/alert.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/common/jquery.validator.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/elearning/common.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/elearning/manage.css">
<link rel="stylesheet" href="http://at.alicdn.com/t/font_1414721846_915907.css" type="text/css"> 
<link rel="stylesheet" href="${ctx }/static/css/elearning/xpTable.css" type="text/css"> 
<!--头部-->   
<%@include file= "../../common/header.jsp"%>
<script type="text/javascript" src="${ctx}/static/js/common/alert.js"></script>
<script type="text/javascript" src="${ctx}/static/js/common/window.js"></script>  
<script type="text/javascript" src="${ctx}/static/js/elearning/jquery.cookie.js"></script> 
<script type="text/javascript" src="${ctx}/static/js/elearning/jquery.formFill.js"></script> 
<script type="text/javascript" src="${ctx}/static/js/elearning/xpTable.js"></script>  
<script type="text/javascript" src="${ctx}/static/js/elearning/xpButton.js"></script>  
<script type="text/javascript" src="${ctx}/static/js/elearning/xpPaginator.js"></script> 
<script type="text/javascript" src="${ctx}/static/js/common/jquery.validator.js"></script> 
<script type="text/javascript" src="${ctx}/static/js/common/zh_CN.js"></script> 
<script type="text/javascript" src="${ctx}/static/js/elearning/fullAvatarEditor/scripts/swfobject.js"></script>
<script type="text/javascript" src="${ctx}/static/js/elearning/fullAvatarEditor/scripts/fullAvatarEditor.js"></script>
<!-- 图片上传 -->
<script type="text/javascript" src="${ctx}/static/js/elearning/jquery.upload.js"></script>

<script type="text/javascript" >
    $(function(){
        //窗体
          var addWin = new Popup({
             btn:'B',
             con:'addDialog',
             closeBtn:'cancel',
             isMask:true,
             zIndex:99
         });
        
          //缓存数据
        var hideattr=$.cookie("TrainerListCookie");
        if(hideattr!=undefined){
            hideattr=JSON.parse($.cookie("TrainerListCookie"));
        }else{
            hideattr={};
        }
        
        //讲师下拉列表
        $.ajax({
            url:"${ctx}/td/trainerType/selectTrainerTypeList.do",
            type:"get",
            success:function(data){
                var option="<option class='optionli' value=''>"+"-- 请选择 --"+ "</option>"; 
                if(data.beans.length!=0){
                      for(var i=0; i<data.beans.length; i++){
                          option+="<option class='optionli' value='"+data.beans[i].id+"'>"+data.beans[i].name+ "</option>";
                          $("#search_trainerTypeId").html(option);
                          $("#trainerTypeId_add").html(option);
                         }
                }
                //下拉绑定事件
                $("#search_trainerTypeId").bind("change",function(){
                    $("#searchbtn").trigger("click");
                });
            }
        });
        
          //标签查询
          getLabels();
          function getLabels(){
              $("#search_labelsId span").remove();
              $.ajax({
                url:"${ctx}/td/trainer/selectAllLables.do",
                type:"get",
                success:function(data){
                    $("#search_labelsId").append("<span class='label label-primary' data-labelId='' data-labelCounts='' onclick=searchFun(this);><a>全部</a></span><span>&nbsp;&nbsp;</span>");
                    if(data.beans.length!=0){
                          for(var i=0; i<data.beans.length; i++){
                              if(i<5){
                                  $("#search_labelsId").append("<span data-labelId='"+data.beans[i].id+"' data-labelCounts='"+data.beans[i].counts+"' onclick=searchFun(this);><a>"+data.beans[i].trainerLabel+"("+data.beans[i].counts+")</a></span><span>&nbsp;&nbsp;</span>");
                              }
                          }
                    }
                }
            });
          }
        
          //搜索
          $("#searchbtn").click(function(){
              table.load({"pageBean.pageNo": 1,name: $.trim($("#search_name").val()),trainerTypeId:$("#search_trainerTypeId").val(),disable:$("#search_disable").val(),labels:$("#search_labelsId").find(".label-primary").attr("data-labelId") } );
          });
          
          //状态下拉绑定事件
        $("#search_disable").bind("change",function(){
            $("#searchbtn").trigger("click");
        });
          
           //表头分组
          var groupCols = [
            {title:"姓名/等级", name:"headImg", align: "left", width:180,renderer: function(val,item,rowIndex){
                var html = "";
                var id = item.id;
                if(item.headImg!=""){
                    html = "<div class='personinfo'><div class='headimg' ><a href=${ctx}/td/trainer/selectTrainerDetails.do?id="+item.id+"><img title='"+item.name+"' src='${ctx}/upload/trainer_picture/"+item.headImg+"' /></a></div><p>姓名:<span title='"+item.name+"'>"+item.name+"</span></p><p>等级:<span title='"+item.title+"'>"+item.title+"</span></p></div>";
                }else{
                    html = "<div class='personinfo'><div class='headimg' ><a href=${ctx}/td/trainer/selectTrainerDetails.do?id="+item.id+"><img title='"+item.name+"' src='${ctx}/static/images/common/head_default.jpg' /></a></div><p>姓名:<span title='"+item.name+"'>"+item.name+"</span></p><p>等级:<span title='"+item.title+"'>"+item.title+"</span></p></div>";
                }
                return html;
              }},
            {title:"讲师类型", name:"trainerTypeName", align: "left", width:50},
            {title:"专业领域 ", name:"proField", align: "left", width:120},
            {title:"简介", name:"intro", align: "left", width:120},
            {title:"标签", name:"labelsName", align: "left", width:150},
            {title:"状态", name:"disable", align: "left", width:20 ,renderer: function(val,item,rowIndex){
                var html = "";
                if(item.disable==1){
                    html = "<div class='personinfo'>启用</div>";
                }else{
                    html = "<div class='personinfo'>禁用</div>";
                }
                return html;
              }}
        ];
           
           //表格
            table = $("#tableshow").xpTable({
              cols: groupCols,
              url:"${ctx}/td/trainer/queryTrainerList.do",
                method: "get",
                fullWidthRows:true,
                height:"auto",
                nowrap:true,
                params:function(){
                    //如果这里有验证,在验证失败时返回false则不执行AJAX查询。
                return {"pageBean.pageNo": 1,name: $.trim($("#name").val()),trainerTypeId:$("#search_trainerTypeId").val() }
                },
                cookieName:"TrainerListCookie",
                checkCol:true,
                multiSelect:true,
              root:"beans",
              plugins:[
                $("#paginator").xpPaginator({}),
                $("#xpButton").xpButton({
                    btns:[{btnName:"新增",btnfn:addTeacher,className:"btn btn-primary",icon:"&#58929;"},{btnName:"修改",btnfn:editTeacher,className:"btn btn-default",icon:"&#58929;"},{btnName:"禁用 ",btnfn:delTeacher,className:"btn btn-default",icon:"&#58929;"},{btnName:"启用 ",btnfn:enableTeacher,className:"btn btn-default",icon:"&#58929;"}]
                })
            ]
            }); 
             
            table.on('cellSelected', function(e, item, rowIndex, colIndex){}).on('loadSuccess', function(e, data){
            var TimeFn = null;                
            $('#tableshow').find("tr").click(function () {
                // 取消上次延时未执行的方法
                clearTimeout(TimeFn);
                //执行延时
                TimeFn = setTimeout(function(){
                },300);
            });        
            $("#tableshow").find("tr").dblclick(function () {   
                if(!$(this).hasClass("emptyRow")){
                    var rowdata=table.row($(this).index());
                    // 取消上次延时未执行的方法
                    clearTimeout(TimeFn);
                    //双击事件的执行代码
                    //location.href="${ctx}/td/trainer/selectTrainerDetails.do?id="+rowdata.id;
                    
                    //弹出修改窗口
                    var html=" <i class='iconfont'id='close_edit'>&#xe629;</i>";
                    $("#addDialog").find(".dialog_title").attr("data-operateType","add").html("修改").append(html);
                    
                    $("#id").val(rowdata.id);
                    $("#name").val(rowdata.name);
                    $("#title").val(rowdata.title);
                    $("#recommend").val(rowdata.recommend);
                    if(rowdata.trainerTypeId!=""){
                        $("#trainerTypeId_add").find("option[value="+rowdata.trainerTypeId+"]").attr("selected",true);
                    }
                    $("#phone").val(rowdata.phone);
                    $("#email").val(rowdata.email);
                    $("#proField").val(rowdata.proField);
                    $("#intro").val(rowdata.intro);
                    //头像
                    if(rowdata.headImg!=""){
                        $("#head_img").attr("src","${ctx}/upload/trainer_picture/"+rowdata.headImg);
                        $("#head_img").attr("data-img",rowdata.headImg);
                    }else{
                        $("#head_img").attr("src","${ctx}/static/images/common/head_default.jpg");
                        $("#head_img").attr("data-img","head_default.jpg");
                    }
                    
                    //标签
                    var trainerLabels = rowdata.labels;
                    $("#tagName").val("");
                    $("#labels li").remove();//清空标签
                    
                    if(trainerLabels!=null){
                        $.ajax({
                            url:"${ctx}/td/trainer/queryLabelListByIds.do",
                            type:"get",
                            data:{trainerLabels : trainerLabels },
                            success:function(data){
                                var bean=data.beans;
                                var html="";
                                if(bean.length!=0){
                                      for(var i=0;i<bean.length;i++){
                                          var data=bean[i];
                                          $(".labels").append("<li class='signli' data-id='"+data.id+"' data-trainerLabel='"+data.trainerLabel+"'><span>"+data.trainerLabel+"</span><i class='iconfont' onclick='delLable(this)'>&#xe629;</i></li>");
                                      }
                                }
                            }
                        });
                        
                    }
                    
                    addWin.showPopup();
                      $("#close_edit").on("click",function(){
                        $("#formId")[0].reset();
                        addWin.close();
                    });
                      
                      createBig(); //初始化验证信息
                }
            });
        });
        
             //添加标签
             $(".addsign").on("mouseover",function(){
            $(".addsign").css("color","#48b8e8").css("cursor","pointer");
             });
          
          //点击上传头像
        $("#head_pic_btn").click(function(){
            $.upload({
                url:'${ctx}/td/trainer/uploadHeadImg.do',
                fileName:'img',
                dataType:'json',
                onComplate:function(data){
                    //删除data中<pre>标签
                    var start = data.indexOf(">");
                    if (start != -1) {
                        var end = data.indexOf("<", start + 1);
                        if (end != -1) {
                            data = data.substring(start + 1, end);
                        }
                    }
                    
                    if(data!==''){
                        $("#head_img").attr("src","${ctx}/upload/trainer_picture/"+data);
                        $("#head_img").attr("data-img",data);
                    }
                }
            });
        });
          
          //新增修改 验证提交
          function createBig(){
              $("#formId").validator({
                    theme :"simple_bottom",
                    rules:{
                      name :[/^[\w\u4e00-\u9fa5]+$/,'不能包含特殊字符'], //匹配中文、数字、字母、下划线
                      sortIndexOnly:function(){}, //sortIndex去重检索
                      nameOnly:function(){},//name去重检索
                  },
                  fields: {
                      name:"姓名:required;length[1~30];name;",
                      title:"等级:length[0~30];name;",
                      phone:"电话:required;mobile;",
                      email:"邮箱:length[0~50];email;",
                      proField:"length[0~200];",
                      intro:"length[0~200];"
                  },
                      valid: function(form){
                          var tname = $(".dialog_title").text();
                          var headImg = $("#head_img").attr("data-img");
                      if(headImg=="head_default.jpg"){
                          headImg=null;
                      }
                      
                          if(tname.indexOf("修改")>=0){
                             //修改保存
                               var labels = "";
                            var index = 0;
                            $(".labels").find("li").each(function(){
                                if(index==0){
                                    labels += "'" + $(this).attr("data-id") + "'";
                                }else{
                                    labels += ",'"+$(this).attr("data-id") + "'";
                                }
                                index++;
                            });
                            
                            var param={id:$("#id").val(),headImg:headImg,name:$.trim($("#name").val()),title:$.trim($("#title").val()),phone:$.trim($("#phone").val()),email:$.trim($("#email").val()),proField:$.trim($("#proField").val()),trainerTypeId:$("#trainerTypeId_add").val(),intro:$.trim($("#intro").val()),labels:labels };   
                              var param_a = {name:$.trim($("#name").val()),phone:$.trim($("#phone").val()),id:$("#id").val() }; 
                              $.ajax({
                                  url:"${ctx}/td/trainer/checkTrainer.do",
                                type:"get",
                                data:param_a,
                                success:function(data){
                                    if(data=="ok"){
                                        $.ajax({
                                                url:"${ctx}/td/trainer/modify.do",
                                              type:"get",
                                              data:param,
                                              success:function(data){
                                                  if(data.result=="true"){
                                                       new AlertWin().initfn({
                                                           "tipscon":data.resultDesc,
                                                           "showtime":2000
                                                       });
                                                       $("#formId")[0].reset();
                                                       addWin.close();
                                                   }else{
                                                       new AlertWin().initfn({
                                                           "tipscon":data.resultDesc,
                                                           "showtime":2000
                                                       }); 
                                                   }
                                                  $("#searchbtn").trigger("click");
                                                  getLabels();
                                              }
                                          });
                                    }else{
                                        new AlertWin().initfn({
                                             "tipscon":'修改失败,该讲师已存在!',
                                             "showtime":2000
                                         });
                                    }
                                    
                                    //销毁验证信息,防止回车提交后,再次弹出时出现验证提示信息
                                      $("#formId").validator("destroy");
                                }
                          });
                            
                         }else{
                             //新增
                               var labels = "";
                            var index = 0;
                            $(".labels").find("li").each(function(){
                                if(index==0){
                                    labels += "'" + $(this).attr("data-id") + "'";
                                }else{
                                    labels += ",'"+$(this).attr("data-id") + "'";
                                }
                                index++;
                            });
                            
                              var param={headImg:headImg,name:$.trim($("#name").val()),title:$.trim($("#title").val()),phone:$.trim($("#phone").val()),email:$.trim($("#email").val()),proField:$.trim($("#proField").val()),trainerTypeId:$("#trainerTypeId_add").val(),intro:$.trim($("#intro").val()),labels:labels }; 
                            
                             var param_a = {name:$.trim($("#name").val()),phone:$.trim($("#phone").val()) }; 
                              $.ajax({
                                  url:"${ctx}/td/trainer/checkTrainer.do",
                                type:"get",
                                data:param_a,
                                success:function(data){
                                    if(data=="ok"){
                                        $.ajax({
                                                url:"${ctx}/td/trainer/insert.do",
                                              type:"get",
                                              data:param,
                                              success:function(data){
                                                  if(data.result=="true"){
                                                      new AlertWin().initfn({
                                                           "tipscon":data.resultDesc,
                                                           "showtime":2000
                                                       });
                                                       $("#formId")[0].reset();
                                                       addWin.close();
                                                   }else{
                                                       new AlertWin().initfn({
                                                           "tipscon":data.resultDesc,
                                                           "showtime":2000
                                                       }); 
                                                   }
                                                  $("#searchbtn").trigger("click"); 
                                                  getLabels();
                                              }
                                          });
                                    }else{
                                        new AlertWin().initfn({
                                             "tipscon":'新增失败,该讲师已存在!',
                                             "showtime":2000
                                         }); 
                                    }
                                    
                                    //销毁验证信息,防止回车提交后,再次弹出时出现验证提示信息
                                      $("#formId").validator("destroy");
                                }
                          });
                              
                         }
                          
                       }
                });
          }
          
          
          //弹出新增窗口
          function addTeacher() {
              
              var html=" <i class='iconfont closeWin' id='close_add'>&#xe629;</i>";
            $("#addDialog").find(".dialog_title").attr("data-operateType","add").html("新增").append(html);
            
            $("#addtag-cancel").trigger("click"); //恢复未点击状态
              //头像
            $("#head_img").attr("src","${ctx}/static/images/common/head_default.jpg");
            $("#head_img").attr("data-img","head_default.jpg");
            $("#labels li").remove();//清空标签
            $("#trainerTypeId_add option:selected").attr("selected",false);//清空下拉框选中项
            
            addWin.showPopup();
            $("#close_add").on("click",function(){
                $("#formId")[0].reset();
                addWin.close();
            });
            
            createBig(); //初始化验证信息
          }
          
        //弹出修改窗口
          function editTeacher() {
              var selectObj = table.selectedRowsIndex();                
            var selectItem = table.row(selectObj[0]);
            
            if(selectObj.length==0){
                new AlertWin().initfn({
                    "tipscon":"请先选择数据!",
                    "showtime":2000
                });
            }else if(selectObj.length>1){
                new AlertWin().initfn({
                    "tipscon":"只能选择一条数据进行修改!",
                    "showtime":2000
                });
            }else if(selectObj.length==1){
                  $("#formId").fill(selectItem);
                  var html=" <i class='iconfont'id='close_edit'>&#xe629;</i>";
                $("#addDialog").find(".dialog_title").attr("data-operateType","add").html("修改").append(html);
                
                $("#addtag-cancel").trigger("click"); //恢复未点击状态
                
                $("#id").val(selectItem.id);
                $("#name").val(selectItem.name);
                $("#title").val(selectItem.title);
                $("#recommend").val(selectItem.recommend);
                
                if(selectItem.trainerTypeId!=""){
                    $("#trainerTypeId_add").find("option[value="+selectItem.trainerTypeId+"]").attr("selected",true);
                }
                $("#phone").val(selectItem.phone);
                $("#email").val(selectItem.email);
                $("#proField").val(selectItem.proField);
                $("#intro").val(selectItem.intro);
                //头像
                if(selectItem.headImg!=""){
                    $("#head_img").attr("src","${ctx}/upload/trainer_picture/"+selectItem.headImg);
                    $("#head_img").attr("data-img",selectItem.headImg);
                }else{
                    $("#head_img").attr("src","${ctx}/static/images/common/head_default.jpg");
                    $("#head_img").attr("data-img","head_default.jpg");
                }
                
                //标签
                var trainerLabels = selectItem.labels;
                $("#tagName").val("");
                $("#labels li").remove();//清空标签
                
                if(trainerLabels!=null){
                    $.ajax({
                        url:"${ctx}/td/trainer/queryLabelListByIds.do",
                        type:"get",
                        data:{trainerLabels : trainerLabels },
                        success:function(data){
                            var bean=data.beans;
                            var html="";
                            if(bean.length!=0){
                                  for(var i=0;i<bean.length;i++){
                                      var data=bean[i];
                                      $(".labels").append("<li class='signli' data-id='"+data.id+"' data-trainerLabel='"+data.trainerLabel+"'><span>"+data.trainerLabel+"</span><i class='iconfont' onclick='delLable(this)'>&#xe629;</i></li>");
                                  }
                            }
                        }
                    });
                    
                }
                
                addWin.showPopup();
                  $("#close_edit").on("click",function(){
                    $("#formId")[0].reset();
                    addWin.close();
                });
                  
                  createBig(); //初始化验证信息
            }
          }
      
          //取消
        $("#cancel").on("click",function(){
            $("#formId")[0].reset();
            addWin.close();
        });
          
          /**
          //删除弹窗 enableTeacher
            function delTeacher(){
                var selectObj = table.selectedRowsIndex();
            var selectData = table.row(selectObj);
            if(selectObj.length==0){
                new AlertWin().initfn({
                    "tipscon":"请先选择数据!",
                    "showtime":2000
                });
            }else{
                new AlertWin().initfn({
                    "havebtn":true,
                    "autohide":false,
                    "fnok": delSelective,
                    "fncancel":null,
                    "focusbtn":"cancel",
                    "title":"温馨提示",
                    "tipscon":"确定要禁用选中的数据吗?"
                });
            }
            }
          */
          
          //禁用
            //function delSelective(){
          function delTeacher(){

            var selectObj = table.selectedRowsIndex();
            var selectData = table.row(selectObj);
            if(selectObj.length==0){
                new AlertWin().initfn({
                    "tipscon":"请先选择数据!",
                    "showtime":2000
                });
            }else{
                var selectIndex= table.selectedRowsIndex();
                  var selectTeacherId = "";
                  for (var i=0;i<selectIndex.length; i++){
                      var selectItem = table.row(selectIndex[i]);
                      if(i==0){
                          selectTeacherId =  selectItem.id;
                      }else{
                          selectTeacherId = selectTeacherId + ","+ selectItem.id;
                      }
                  }
                param = { id:selectTeacherId,disable:2 };
                
                $.ajax({
                    url:"${ctx}/td/trainer/delete.do",
                    type:"get",
                    data:param,
                    success:function(data){
                        new AlertWin().initfn({
                            "tipscon":data.resultDesc,
                            "showtime":2000
                        });
                        $("#searchbtn").trigger("click"); 
                        getLabels();
                    }
                });     
            }
              
            }
          
          /**
          //启用弹窗 enableTeacher
            function enableTeacher(){
                var selectObj = table.selectedRowsIndex();
            var selectData = table.row(selectObj);
            if(selectObj.length==0){
                new AlertWin().initfn({
                    "tipscon":"请先选择数据!",
                    "showtime":2000
                });
            }else{
                new AlertWin().initfn({
                    "havebtn":true,
                    "autohide":false,
                    "fnok": enableSelective,
                    "fncancel":null,
                    "focusbtn":"cancel",
                    "title":"温馨提示",
                    "tipscon":"确定要启用选中的数据吗?"
                });
            }
            }
          */
          
          //启用
            //function enableSelective(){
          function enableTeacher(){
              var selectObj = table.selectedRowsIndex();
            var selectData = table.row(selectObj);
            if(selectObj.length==0){
                new AlertWin().initfn({
                    "tipscon":"请先选择数据!",
                    "showtime":2000
                });
            }else{
                var selectIndex= table.selectedRowsIndex();
                  var selectTeacherId = "";
                  for (var i=0;i<selectIndex.length; i++){
                      var selectItem = table.row(selectIndex[i]);
                      if(i==0){
                          selectTeacherId =  selectItem.id;
                      }else{
                          selectTeacherId = selectTeacherId + ","+ selectItem.id;
                      }
                  }
                param = { id:selectTeacherId,disable:1 };
                $.ajax({
                    url:"${ctx}/td/trainer/delete.do",
                    type:"get",
                    data:param,
                    success:function(data){
                        new AlertWin().initfn({
                            "tipscon":data.resultDesc,
                            "showtime":2000
                        });
                        $("#searchbtn").trigger("click"); 
                        getLabels();
                    }
                });      
            }
            }
            
        $(".addtag").click(function(){
            var num = $("#labels").find("li").length; //标签个数
            if(num<10){
                $(this).hide();
                $(".taginput").show();
            }else{
                new AlertWin().initfn({
                    "tipscon":"最多只能添加十个标签!",
                    "showtime":2000
                });
            }
            
        });
        
        //添加标签 取消
        $("#addtag-cancel").click(function(){
            $("#tagName").val("");
            $(".taginput").hide();
            $(".addtag").show();
            
        });
        
        //添加标签 确定
        $("#addtag-ok").click(function(){
            var word = $.trim($("#tagName").val());
            
            if(word!=""){
                var tagName = $("#tagInfo").attr("data-trainerLabel");
                var tagId = $("#tagInfo").attr("data-id");
                
                //判断标签是否已存在
                if(tagName!=="" && tagId!==""){
                    //不存在
                    if($(".labels").find("li[data-trainerLabel='"+tagName+"']").length==0){
                        $(".labels").append("<li class='signli' data-id='"+tagId+"' data-trainerLabel='"+tagName+"'><span>"+tagName+"</span><i class='iconfont' onclick='delLable(this)'>&#xe629;</i></li>");
                        $("#addtag-cancel").trigger("click");
                    }else{
                        new AlertWin().initfn({
                            "tipscon":"标签已存在不能重复添加",
                            "showtime":2000
                        });
                    }
                }else{
                    //不存在 新增到数据库
                    if($(".labels").find("li[data-trainerLabel='"+word+"']").length==0){
                        var param = {trainerLabel:word};
                        $.ajax({
                            url: "${ctx}/td/trainer/insertLabel.do",
                            data: param,
                            success: function(data){
                                if(data.result=="true"){
                                    $(".labels").append("<li class='signli' data-id='"+data.resultDesc+"' data-trainerLabel='"+word+"'><span>"+word+"</span><i class='iconfont' onclick='delLable(this)'>&#xe629;</i></li>");
                                    $("#addtag-cancel").trigger("click");
                                }
                            }
                        });
                    }
                }
            }
        });
        
        creatSelectDiv($("#tagName"));
        //生成项目选择下拉框
        function creatSelectDiv(obj){
            var selectInput = $(obj);
            var cityIdInput = $("#tagInfo");
            var width = selectInput.width() + 10;
            var selectDiv = selectInput.parent();
            selectDiv.find("ul").remove();
            selectDiv.append("<ul style='height:200px;overflow:auto;'></ul>");
            var selectUl = selectDiv.find("ul");
            ctiyIsShow = true;
            selectUl.css({
                width:width+"px"
            });
            
            selectInput.focus(function(){
                cityIdInput.attr("data-trainerLabel","").attr("data-id","");
                keycode = event.keyCode;
                if(keycode!=40 && keycode!=38 && keycode!=13){
                    var word =  $.trim(selectInput.val());
                    $.ajax({
                        url:"${ctx}/td/trainer/queryLabelList.do",
                        type:"get",
                        data:{trainerLabel:word},
                        success:function(data){
                            var bean=data.beans;
                            var html="";
                            if(bean.length==0){
                                //html=html+"<div>没找到匹配项!</div>";
                                selectUl.hide();
                            }else{
                                for(var i=0;i<bean.length;i++){
                                    var data=bean[i];
                                    html=html+"<li data-id='"+data.id+"' data-trainerLabel='"+data.trainerLabel+"'>"+data.trainerLabel+"</li>";                                
                                }
                                selectUl.html(html).show();
                                selectUl.find("li").eq(0).addClass("cur");                                
                            }
                            selectUl.find("li").bind("click",function(){
                                selectInput.val($(this).attr("data-trainerLabel"));
                                cityIdInput.attr("data-trainerLabel",$(this).attr("data-trainerLabel")).attr("data-id",$(this).attr("data-id"));
                                selectUl.html("").hide();
                            });
                            selectUl.find("li").bind("mouseover",function(){
                                $(this).addClass("cur").siblings().removeClass("cur");
                            });
                        }
                    });
                }
                selectUl.show();
            });
            
            selectInput.keyup(function(event){
                keycode = event.keyCode;
                if(keycode!=40 && keycode!=38 && keycode!=13){
                    var word =  $.trim(selectInput.val());
                    $.ajax({
                        url:"${ctx}/td/trainer/queryLabelList.do",
                        type:"get",
                        data:{trainerLabel:word},
                        success:function(data){
                            var bean=data.beans;
                            var html="";
                            if(bean.length==0){
                                //html=html+"<div>没找到匹配项!</div>";
                                selectUl.hide();
                            }else{
                                  for(var i=0;i<bean.length;i++){
                                      var data=bean[i];
                                      html=html+"<li data-id='"+data.id+"' data-trainerLabel='"+data.trainerLabel+"'>"+data.trainerLabel+"</li>";                            
                                  }
                                  selectUl.html(html).show();
                                  selectUl.find("li").eq(0).addClass("cur");                                  
                            }
                            selectUl.find("li").bind("click",function(){
                                selectInput.val($(this).attr("data-trainerLabel"));
                                cityIdInput.attr("data-trainerLabel",$(this).attr("data-trainerLabel")).attr("data-id",$(this).attr("data-id"));
                                selectUl.html("").hide();
                                
                            });
                            
                            selectUl.find("li").bind("mouseover",function(){
                                $(this).addClass("cur").siblings().removeClass("cur");
                            });
                        }
                    });
                }
            });
            
            selectUl.mouseover(function(){
                ctiyIsShow = false;
            });
            
            selectUl.mouseout(function(){
                ctiyIsShow = true;
                var index = selectUl.find("li.cur").index();
                if(index!=-1){
                }
            });
            
            selectInput.blur(function(){
                if(ctiyIsShow){
                    var index = selectUl.find("li.cur").index();
                    var word = $.trim(selectInput.val());
                    if(selectUl.find("li[data-trainerLabel='"+word+"']").length>0){
                        cityIdInput.attr("data-trainerLabel",selectUl.find("li[data-trainerLabel='"+word+"']").attr("data-trainerLabel"));
                        cityIdInput.attr("data-id",selectUl.find("li[data-trainerLabel='"+word+"']").attr("data-id"));
                    };
                    
                    if(index!=-1){
                        
                    }
                    
                    selectUl.html("").hide();
                }
            });
            
            $(document).keyup(function(event){                 
                keycode = event.keyCode;
                if(selectInput.is(":focus")){                    
                    index = selectUl.find("li.cur").index();
                    var li = selectUl.find("li");                    
                    switch (keycode){
                        case 40:                            
                            if(index == -1){
                                li.eq(0).addClass("cur");
                            }else{
                                li.eq(index).next().addClass("cur").siblings().removeClass("cur");
                            }
                        break;
                        
                        case 38:
                            if(index != -1){
                                li.eq(index).prev().addClass("cur").siblings().removeClass("cur");
                            }
                        break;
                        
                        case 13:
                            if(index != -1){
                                selectUl.html("").hide();
                            }                            
                        break;
                    }
                }
            });
            
        }
        
        //阻止冒泡
        function stopPropagation(e) { 
            if (e.stopPropagation){
                e.stopPropagation(); 
            }else {
                e.cancelBubble = true; 
            }
        } 
        
        //搜索课程
        $("#courseSeachBtn").bind("click",function(){
            location.href = "${ctx}/views/elearning/studycenter/stucenter.jsp?keyword="+$.trim($("#courseName").val());
        });
        
        //回车事件
        $(document).keyup(function(event){
            //搜索课程
            if($("#courseName").is(":focus")&&event.keyCode=="13"){
                $("#courseSeachBtn").trigger("click"); 
            }
            //按姓名搜索
            if($("#search_name").is(":focus")&&event.keyCode=="13"){
                $("#searchbtn").trigger("click");
            }
            //添加标签
            if($("#tagName").is(":focus")&&event.keyCode=="13"){
                $("#addtag-ok").trigger("click"); 
            }
            //提交表单
            if($("#name").is(":focus")&&event.keyCode=="13"){
                $("#formId").submit(); 
            }
            //提交表单
            if($("#phone").is(":focus")&&event.keyCode=="13"){
                $("#formId").submit(); 
            }
            
        });
        
    });
    
    //删除标签
    function delLable(obj){
        $(obj).parent().remove();
        
        //查看这个标签是否被其它地方引用,没有则从数据库中删除
        var param = {id:$("#id").val(), labels:$(obj).parent().attr("data-id") };
        $.ajax({
            url: "${ctx}/td/trainer/checkLabelCounts.do",
            data: param,
            success: function(data){
                if(data=="ok"){
                    
                }
            }
        });
        
    }
    
      //标签查询
    function searchFun(obj){
        $(obj).siblings().removeClass("label label-primary");
        $(obj).addClass("label label-primary");
        $("#searchbtn").trigger("click"); 
    }
      
</script>

</head>
<body class="manageteacher">
    <!--头部  -->
    <div class="study_bar clearfix">
         <div class="bd">
            <div class="studytitle">培训讲师管理</div>
            <div class="search">
                <input class="input_text" id="courseName" type="input" placeholder="搜索在线学习教程" value=""/>
                <i class="iconfont">&#xe605;</i>
                <button class="searchbtn" id="courseSeachBtn">搜索</button>
                <a class="link" href="${ctx}/views/elearning/studycenter/allcourse.jsp">全部课程</a>
            </div>
            <div class="clearfix"></div>
            <ol class="breadcrumb">
                <li><i class="iconfont index">&#xe672;</i><a href="${ctx}/emp/index.do">管理与服务</a></li>
                <li><i class="iconfont">&#xe622;</i><a href="${ctx}/emp/index.do#pxhd">培训管理</a></li>
                <li><i class="iconfont">&#xe622;</i><a>培训讲师</a></li>
            </ol>
        </div>
       </div>
           
    <!-- 内容部分 -->
    <div class="centercontent">
        <!-- 搜索部分 -->
        <div class="search clearfix">
            <div class="search_top clearfix">
                <div class="search_input">
                         <div class="input-group input-group-sm">
                        <span class="input-group-addon">姓名</span>
                        <input type="text"  class="form-control" style="font-size:14px;" id="search_name" name="name" placeholder="请输入姓名" >
                    </div>
                    </div>
                    <div class="search_input">
                            <div class="input-group input-group-sm">
                        <span class="input-group-addon">类型</span>
                        <select class="form-control" id="search_trainerTypeId" name="trainerTypeId" style="width:157px;height:32px;font-size:14px;"></select>
                       </div>
                    </div>
                    <div class="search_input">
                            <div class="input-group input-group-sm">
                        <span class="input-group-addon">状态</span>
                        <select class="form-control" id="search_disable" name="disable" style="width:157px;height:32px;font-size:14px;">
                            <option value="">-- 全部 --</option>
                            <option value="1">启用</option>
                            <option value="2">禁用</option>
                        </select>
                       </div>
                    </div>
                <span>&nbsp;</span>
                      <button type="button" class="btn btn-success" id="searchbtn" >搜索</button> 
                      <div class="button_list r" id="xpButton"></div>
                 
                      
              </div>
            <div class="sign">
                <span class="sign_span">标签:</span>
                <div class="sign_div" id="search_labelsId"></div>
            </div>
            
        </div>
        
        <!-- 数据展示 -->
        <div class="tmanage">
              <table id="tableshow" class="table"></table>
              <div class="page_div" id="paginator"></div>
        </div>
        
        <!-- 弹窗  开始  -->
        <div class="dialog_teachermanage" id="addDialog" style="width:860px; display:none" >
              <div class="dialog_title" data-operateType="add"></div>
              <form id="formId" method="post" enctype="multipart/form-data" onkeydown="if(event.keyCode==13)return false;" >
                  <div class="dialog_body">                  
                      <div class="left">
                          
                          <!-- 上传头像  ajax提交  class="hide"  -->
                          <div class="head_photo">
                              <a id="head_pic_btn">点击上传头像</a>
                              <img src="${ctx}/static/images/common/head_default.jpg" data-img="head_default.jpg" width="180px" height="210px" id="head_img" />
                          </div>
                          
                          <div class="clear" style="height:30px;"></div>
                          <!-- 隐藏的标签查询、输入框 -->
                          <div class="addsign" id="addCourse">
                              <div class="tagdiv">
                                <a class="addtag"><i class='iconfont'>&#xe623;</i>添加标签</a>
                                <div class="taginput clearfix">
                                    <input class="form-control" id="tagName" type="text" />
                                    <i class="iconfont ok" id="addtag-ok">&#xe626;</i>
                                    <i class="iconfont cancel" id="addtag-cancel">&#xe627;</i>
                                </div>
                            </div>
                          </div>
                          <ul class="singul labels" name="labels" id="labels"></ul>
                      </div>
                      
                      <div class="right">
                          <input type="hidden" id="id" name="id">
                          <div class="right_tinput">
                              <span class="t_span">姓名</span>
                              <input type="text" name="name" id="name" placeholder="30字以内"/>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">等级</span>
                              <input type="text" name="title" id="title" placeholder="30字以内"/>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">电话</span>
                              <input type="text" name="phone" id="phone" placeholder="请输入电话号码"/>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">邮箱地址</span>
                              <input type="text" name="email" id="email" placeholder="请输入邮箱地址"/>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">讲师类型</span>
                              <select id="trainerTypeId_add"  name="trainerTypeId" placeholder="请选择"/></select>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">专业领域</span>
                              <textarea  cols="20" rows="3" name="proField" id="proField" placeholder="200字以内" ></textarea>
                          </div>
                          <div class="right_tinput">
                              <span class="t_span">简介</span>
                              <textarea cols="20" rows="3" name="intro" id="intro" placeholder="200字以内" ></textarea>
                          </div>
                          
                          <div class="dialog_bottom">
                              <div class="buttons">
                                  <button type="button" id="cancel">取消</button>
                                  <button type="submit" >保存</button>
                                </div>
                          </div>
                      </div>
                  </div>
                  
              </form>
          </div>
          <!-- 弹窗  结束  -->
          
    </div>
    <input type="hidden" id="B" />
    <input type="hidden" id="tagInfo" />
</body>
</html>
View Code

 

 

禁止按回车键提交表单:在form标签中加入: onkeydown="if(event.keyCode==13)return false;"

<form id="formId" method="post" enctype="multipart/form-data" onkeydown="if(event.keyCode==13)return false;" >

</form>


后台:

package com.dayhr.web.module.hr.td.elearn.controler;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.dayhr.common.util.ImgUtil;
import com.dayhr.common.util.OperateImage;
import com.dayhr.employee.response.EmpMessageRes;
import com.dayhr.privilege.domain.User;
import com.dayhr.web.module.base.BaseController;
import com.dayhr.web.module.base.Data;
import com.dayhr.web.module.base.MessageResp;
import com.dayhr.web.module.hr.td.elearn.model.AttentionTrainer;
import com.dayhr.web.module.hr.td.elearn.model.TrainCourse;
import com.dayhr.web.module.hr.td.elearn.model.Trainer;
import com.dayhr.web.module.hr.td.elearn.model.TrainerLabel;
import com.dayhr.web.module.hr.td.elearn.param.AttentionTrainerQueryParam;
import com.dayhr.web.module.hr.td.elearn.param.TrainCourseQueryParam;
import com.dayhr.web.module.hr.td.elearn.param.TrainerLabelQueryParam;
import com.dayhr.web.module.hr.td.elearn.param.TrainerQueryParam;
import com.dayhr.web.module.hr.td.elearn.response.AttentionTrainerResp;
import com.dayhr.web.module.hr.td.elearn.response.TrainerLabelResp;
import com.dayhr.web.module.hr.td.elearn.response.TrainerResp;
import com.dayhr.web.module.hr.td.elearn.service.IAttentionTrainerService;
import com.dayhr.web.module.hr.td.elearn.service.ITrainCourseService;
import com.dayhr.web.module.hr.td.elearn.service.ITrainerLabelService;
import com.dayhr.web.module.hr.td.elearn.service.ITrainerService;
import com.dayhr.web.platform.exception.AjaxBusinessException;
import com.dayhr.web.platform.pagination.PageBean;
import com.dayhr.web.platform.pagination.PageUtil;
import com.dayhr.web.util.SessionUtils;
import com.dayhr.web.util.UUIDUtil;

/**
 * 
 * @ClassName:TrainerController
 * @Description: 培训讲师 
 * @author: 
 * @date:2015-2-13 下午3:48:25 
 * @version 1.0
 */
@Controller
@RequestMapping("/td/trainer")
public class TrainerController extends BaseController {
    
    private Logger logger = Logger.getLogger(TrainerController.class);

    @Autowired
    private ITrainerService trainerService;
    
    @Autowired
    private ITrainerLabelService trainerLabelService; //讲师标签
    
    @Autowired
    private IAttentionTrainerService attentionTrainerService; //关注
    
    @Autowired
    private ITrainCourseService<TrainCourse> trainCourseService;//培训课程控制类
    /**
     * 
     * @Title: selectListById 
     * @Description: 根据ID查询数据
     * @param @param id
     * @param @param request
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("/selectListById")
    @ResponseBody
    public Data selectListById(String id, HttpServletRequest request) {
        
        User u = SessionUtils.getUser(request.getSession());
        List<TrainerResp> list = new ArrayList<TrainerResp>();
        
        TrainerResp trainerResp = (TrainerResp) trainerService.selectById(id);
        
        list.add(trainerResp);
        Data data = new Data(list);
        data.setBeans(list);
        
        return data;

    }
    
    /**
     * 
     * @Title: selectTrainerDetails 
     * @Description: 查看讲师详情 
     * @param @param model
     * @param @param params
     * @param @param request
     * @param @return
     * @return ModelAndView
     * @throws
     */
    @RequestMapping("/selectTrainerDetails")
    public ModelAndView selectTrainerDetails(Model model, TrainerQueryParam params, HttpServletRequest request) {
        
        ModelAndView view = new ModelAndView();
        //User u = SessionUtils.getUser(request.getSession());
        //List<TrainerResp> trList = new ArrayList<TrainerResp>();
        
        TrainerResp trainerResp = new TrainerResp();
        if(params.getId()!=null){
            trainerResp = (TrainerResp) trainerService.selectById(params.getId());//获取讲师基本信息
        }
        
        AttentionTrainerQueryParam atparam = new AttentionTrainerQueryParam();
        atparam.setTrainerId(params.getId());
        
        //关注讲师的人信息
        PageBean pageBean = params.getPageBean();
        int count = attentionTrainerService.selectAttentionCount(atparam);// 查询某讲师所有关注信息 总数
        pageBean.setPageCount(String.valueOf(count));// 总页数
        
        Data data = new Data(pageBean);
        int offSet = PageUtil.setParameter(count, params.getPageBean());
        RowBounds row = new RowBounds(offSet, Integer.valueOf(params.getPageBean().getPageSize()));
        List<AttentionTrainerResp> srList = attentionTrainerService.selectAttentionList(atparam, row);//获取关注讲师的人的信息
        
        //trList.add(trainerResp);
        model.addAttribute("trainerResp", trainerResp);
        model.addAttribute("srList", srList);
        
        view.setViewName("views/elearning/manage/teacherinfo");
        
        return view;

    }
    
    /**
     * 
     * @Title: selectAll 
     * @Description: 查询所有数据
     * @param @param request
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("/selectAll")
    @ResponseBody
    public Data selectAll(HttpServletRequest request) {

        User u = SessionUtils.getUser(request.getSession());
        
        List<TrainerResp> list = trainerService.selectAll();

        Data data = new Data(list);
        data.setBeans(list);

        return data;

    }
    
    /**
     * 
     * @Title: checkTrainer 
     * @Description: 验证讲师是否存在
     * @param @param request
     * @param @param params
     * @param @return
     * @return String
     * @throws
     */
    @RequestMapping("checkTrainer")
    @ResponseBody
    public String checkTrainer(HttpServletRequest request, TrainerQueryParam params) {
        
        int corpId = SessionUtils.getCorpId(request.getSession());
        params.setCorpId(corpId);
        int nums = 0;
        nums = trainerService.checkTrainer(params);
        
        String str = "";
        if (nums == 0) {
            //str = "{\"ok\":\"\"}";
            str = "ok";
        } else {
            //str = "{\"error\":\"该名称已经存在!\"}";
            str = "error";
        }
        
        return str;
    }
    
    /**
     * 
     * @Title: insert 
     * @Description: 新增 
     * @param @param params
     * @param @param request
     * @param @return
     * @return MessageResp
     * @throws
     */
    @RequestMapping("/insert")
    @ResponseBody
    public MessageResp insert(TrainerQueryParam params, HttpServletRequest request) {
        MessageResp resp = new MessageResp();
        User u = SessionUtils.getUser(request.getSession());

        /**
         * 把前端传过来的参数对象中要更新的属性转到model实体类相应的字段属性中, 可以通过通用的转化实现
         * */
        Trainer trainer = new Trainer();
        
        try {
            BeanUtils.copyProperties(trainer, params);//前面的是目标,后面的是源对象
        } catch (IllegalAccessException e) {
            throw new AjaxBusinessException("新增出错!");
        } catch (InvocationTargetException e) {
            throw new AjaxBusinessException("新增出错!");
        }
        
        trainer.setId(UUIDUtil.getUUID()); //ID
        trainer.setCorpId(SessionUtils.getCorpId(request.getSession()));
        trainer.setDisable(1);//启用
        
        try {
            
            if (trainerService.insert(trainer) == 1) {
                resp.setResult("true");
                resp.setResultDesc("新增成功!");
            }
        } catch (Exception e) {
            resp.setResult("false");
            resp.setResultDesc("新增出错!");
        }
        
        return resp;
    }
    
    
    /**
     * 
     * @Title: modify 
     * @Description: 修改数据 
     * @param @param params
     * @param @param request
     * @param @return
     * @return MessageResp
     * @throws
     */
    @RequestMapping("modify")
    @ResponseBody
    public MessageResp modify(TrainerQueryParam params, HttpServletRequest request) {

        MessageResp resp = new MessageResp();
        User u = SessionUtils.getUser(request.getSession());
        Trainer trainer = new Trainer();
        
        try {
            BeanUtils.copyProperties(trainer, params);
        } catch (IllegalAccessException e) {
            throw new AjaxBusinessException("修改出错!");
        } catch (InvocationTargetException e) {
            throw new AjaxBusinessException("修改出错!");
        }
        
        if (trainerService.update(trainer) > 0) {
            resp.setResult("true");
            resp.setResultDesc("修改成功!");
        } else {
            resp.setResult("false");
            resp.setResultDesc("更新出错!");
        }
        return resp;

    }
    
    /**
     * 
     * @Title: delete 
     * @Description: 删除讲师信息
     * @param @param params
     * @param @param request
     * @param @return
     * @return MessageResp
     * @throws
     */
    @RequestMapping("delete")
    @ResponseBody
    public MessageResp delete(TrainerQueryParam params, HttpServletRequest request) {
        
        MessageResp resp = new MessageResp();
        TrainCourseQueryParam tcparams = new TrainCourseQueryParam();
        TrainerQueryParam tqp = new TrainerQueryParam();
        
        try {
            //批量删除
            if ((params.getId()).indexOf(",") >= 0) {
                String[] arr = (params.getId()).split(",");
                
                //查询是否有讲师已经有过培训记录(有过则不能删除)
                int sum = 0;
                for (int i = 0; i < arr.length; i++) {
                    tcparams.setTrainerId(arr[i]);//讲师ID
                    int count = trainCourseService.selectCountByTrainerId(tcparams);// 总数
                    
                    if(count>0){
                        sum++;
                    }
                }
                
                if(sum>0){
                    resp.setResult("false");
                    resp.setResultDesc("操作失败,有讲师已经有培训记录,不能被禁用!");
                }else{
                    for (int i = 0; i < arr.length; i++) {
                        tqp.setId(arr[i]);
                        tqp.setDisable(params.getDisable()); //是否禁用:1-启用;2-禁用;
                        trainerService.updateTrainerStatus(tqp); //启用、禁用讲师
                    }
                    resp.setResult("true");
                    resp.setResultDesc("操作成功!");
                }

            } else {//单个删除
                
                tcparams.setTrainerId(params.getId());//讲师ID
                int count = trainCourseService.selectCountByTrainerId(tcparams);// 总数
                
                if (count==0) {
                    tqp.setId(params.getId());
                    tqp.setDisable(params.getDisable()); //是否禁用:1-启用;2-禁用;
                    trainerService.updateTrainerStatus(tqp);
                    
                    resp.setResult("true");
                    resp.setResultDesc("操作成功!");
                }else{
                    resp.setResult("false");
                    resp.setResultDesc("操作失败,该讲师已经有培训记录,不能被禁用!");
                }
            }
            
        } catch (Exception e) {
            resp.setResult("false");
            resp.setResultDesc("操作出错!");
        }
        return resp;
    }
    
    /**
     * 
     * @Title: queryTrainerList 
     * @Description: 查询 讲师管理 
     * @param @param request
     * @param @param params
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("queryTrainerList")
    @ResponseBody
    public Data queryTrainerList(HttpServletRequest request, TrainerQueryParam params) {
        User u = SessionUtils.getUser(request.getSession());
        int empId = SessionUtils.getEmpId(request.getSession());
        
        int corpId = SessionUtils.getCorpId(request.getSession());
        params.setCorpId(corpId);
        params.setOrderBy("t.disable");
        params.setSortType("ASC");
        
        PageBean pageBean = params.getPageBean();
        int count = trainerService.countByCondition(params);
        pageBean.setPageCount(String.valueOf(count));// 总页数

        int offSet = PageUtil.setParameter(count, params.getPageBean());
        RowBounds row = new RowBounds(offSet, Integer.valueOf(params.getPageBean().getPageSize()));
        List<TrainerResp> srList = trainerService.selectListByCondition(params, row);
        
        //标签
        if(srList.size()>0){
            for(int i=0;i<srList.size();i++){
                List<TrainerLabelResp> labellist = srList.get(i).getTrainerLabels();
                
                if(labellist!=null && labellist.size()>0){
                    String labels="";
                    for(int m=0;m<labellist.size();m++){
                        if(m!=labellist.size()-1){
                            labels+=labellist.get(m).getTrainerLabel()+"、";
                        }else{
                            labels+=labellist.get(m).getTrainerLabel();
                        }
                    }
                    srList.get(i).setLabelsName(labels);
                }
            }
        }
        
        Data data = new Data(srList);
        data.setPb(pageBean);
        data.setBeans(srList);

        return data;
    }
    
    /**
     * 
     * @Title: queryAttentionTrainerList 
     * @Description: 查询我关注的讲师
     * @param @param request
     * @param @param params
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("queryAttentionTrainerList")
    @ResponseBody
    public Data queryAttentionTrainerList(HttpServletRequest request, TrainerQueryParam params) {
        
        //User u = SessionUtils.getUser(request.getSession());
        //int corpId = SessionUtils.getCorpId(request.getSession());
        
        int empId = SessionUtils.getEmpId(request.getSession());
        
        params.setUserId(empId);//用户empId
        //params.setOrderBy("t.disable");
        //params.setSortType("ASC");
        
        PageBean pageBean = params.getPageBean();
        int count = trainerService.queryAttentionTrainerListCount(params);
        pageBean.setPageCount(String.valueOf(count));// 总页数

        int offSet = PageUtil.setParameter(count, params.getPageBean());
        RowBounds row = new RowBounds(offSet, Integer.valueOf(params.getPageBean().getPageSize()));
        List<TrainerResp> srList = trainerService.queryAttentionTrainerList(params, row);
        
        Data data = new Data(srList);
        data.setPb(pageBean);
        data.setBeans(srList);

        return data;
    }
    
    /**
     * 
     * @Title: queryTrainerListByName 
     * @Description: 通过讲师姓名查询讲师信息 
     * @param @param request
     * @param @param params
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("queryTrainerListByName")
    @ResponseBody
    public Data queryTrainerListByName(HttpServletRequest request, TrainerQueryParam params) {
        User u = SessionUtils.getUser(request.getSession());
        int empId = SessionUtils.getEmpId(request.getSession());
        
        int corpId = SessionUtils.getCorpId(request.getSession());
        params.setCorpId(corpId);

        List<TrainerResp> srList = trainerService.queryTrainerListByName(params); //通过讲师姓名查询讲师信息 
        
        Data data = new Data(srList);
        data.setBeans(srList);

        return data;
    }
    
    /**
     * 
     * @Title: insertLabel 
     * @Description: 新增标签
     * @param @param params
     * @param @param request
     * @param @return
     * @return MessageResp
     * @throws
     */
    @RequestMapping("/insertLabel")
    @ResponseBody
    public MessageResp insertLabel(TrainerLabelQueryParam params, HttpServletRequest request) {
        MessageResp resp = new MessageResp();
        User u = SessionUtils.getUser(request.getSession());
        
        /**
         * 把前端传过来的参数对象中要更新的属性转到model实体类相应的字段属性中, 可以通过通用的转化实现
         * */
        TrainerLabel trainerLabel = new TrainerLabel();
        
        try {
            BeanUtils.copyProperties(trainerLabel, params);//前面的是目标,后面的是源对象
        } catch (IllegalAccessException e) {
            throw new AjaxBusinessException("新增出错!");
        } catch (InvocationTargetException e) {
            throw new AjaxBusinessException("新增出错!");
        }
        
        trainerLabel.setId(UUIDUtil.getUUID()); //ID
        trainerLabel.setCorpId(SessionUtils.getCorpId(request.getSession()));
        trainerLabel.setCreaterId(u.getUserId());
        trainerLabel.setCreaterTime(new Date());
        
        try {
            if (trainerLabelService.insert(trainerLabel) == 1) {
                resp.setResult("true");
                resp.setResultDesc(trainerLabel.getId()); //返回ID
            }
        } catch (Exception e) {
            resp.setResult("false");
            resp.setResultDesc("新增出错!");
        }
        
        return resp;
    }

    /**
     * 
     * @Title: checkLabel 
     * @Description: 验证标签是否存在
     * @param @param request
     * @param @param params
     * @param @return
     * @return String
     * @throws
     */
    @RequestMapping("checkLabel")
    @ResponseBody
    public String checkLabel(HttpServletRequest request, TrainerLabelQueryParam params) {
        
        int corpId = SessionUtils.getCorpId(request.getSession());
        params.setCorpId(corpId);
        String id = params.getId();
        int nums = 0;
        nums = trainerLabelService.checkLabel(params);
        
        String str = "";
        if (nums == 0) {
            str = "{\"ok\":\"\"}";
        } else {
            str = "{\"error\":\"该名称已经存在!\"}";
        }
        
        return str;
    }
    
    /**
     * 
     * @Title: queryLabelList 
     * @Description: 按条件查询标签
     * @param @param request
     * @param @param params
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("queryLabelList")
    @ResponseBody
    public Data queryLabelList(HttpServletRequest request, TrainerLabelQueryParam params) {
        //User u = SessionUtils.getUser(request.getSession());
        int corpId = SessionUtils.getCorpId(request.getSession());
        params.setCorpId(corpId);
        
        List<TrainerLabelResp> srList = trainerLabelService.selectLabelList(params);
        
        Data data = new Data(srList);
        data.setBeans(srList);

        return data;
    }
    
    /**
     * 
     * @Title: queryLabelListByIds 
     * @Description: 通过ID串查询标签List
     * @param @param request
     * @param @param trainerLabels
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("queryLabelListByIds")
    @ResponseBody
    public Data queryLabelListByIds(HttpServletRequest request, String trainerLabels) {
        
        List<TrainerLabelResp> srList = trainerLabelService.queryLabelListByIds(trainerLabels); //通过ID串查询标签List
        
        Data data = new Data(srList);
        data.setBeans(srList);

        return data;
    }
    
    /**
     * 
     * @Title: selectAllLables 
     * @Description: 查询所有标签、标签使用数目 
     * @param @param request
     * @param @param params
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("selectAllLables")
    @ResponseBody
    public Data selectAllLables(HttpServletRequest request, TrainerLabelQueryParam params) {
        int corpId = SessionUtils.getCorpId(request.getSession());
        params.setCorpId(corpId);
        
        List<TrainerLabelResp> srList = trainerLabelService.selectAllLables(params); //查询所有标签、标签使用数目 
        
        Data data = new Data(srList);
        data.setBeans(srList);

        return data;
    }
    
    /**
     * 
     * @Title: checkAttention 
     * @Description: 判断用户是否关注该讲师 
     * @param @param request
     * @param @param params
     * @param @return
     * @return String
     * @throws
     */
    @RequestMapping("checkAttention")
    @ResponseBody
    public String checkAttention(HttpServletRequest request, AttentionTrainerQueryParam params) {
        
        User u = SessionUtils.getUser(request.getSession());
        //params.setUserId(u.getUserId());
        params.setUserId(SessionUtils.getEmpId(request.getSession()));
        
        int nums = 0;
        nums = attentionTrainerService.checkAttention(params);
        
        String str = "";
        if (nums == 0) {
            str = "{\"error\":\"未关注!\"}";
        } else {
            str = "{\"ok\":\"已关注!\"}";
        }
        
        return str;
    }
    
    /**
     * 
     * @Title: addAttention 
     * @Description: 添加关注
     * @param @param params
     * @param @param request
     * @param @return
     * @return MessageResp
     * @throws
     */
    @RequestMapping("/addAttention")
    @ResponseBody
    public MessageResp addAttention(AttentionTrainerQueryParam params, HttpServletRequest request) {
        MessageResp resp = new MessageResp();
        User u = SessionUtils.getUser(request.getSession());

        /**
         * 把前端传过来的参数对象中要更新的属性转到model实体类相应的字段属性中, 可以通过通用的转化实现
         * */
        AttentionTrainer attentionTrainer = new AttentionTrainer();
        
        try {
            BeanUtils.copyProperties(attentionTrainer, params);//前面的是目标,后面的是源对象
        } catch (IllegalAccessException e) {
            throw new AjaxBusinessException("新增出错!");
        } catch (InvocationTargetException e) {
            throw new AjaxBusinessException("新增出错!");
        }
        
        attentionTrainer.setId(UUIDUtil.getUUID()); //ID
        //attentionTrainer.setUserId(u.getUserId());
        attentionTrainer.setUserId(SessionUtils.getEmpId(request.getSession()));
        
        try {
            if (attentionTrainerService.insert(attentionTrainer) == 1) {
                resp.setResult("true");
                resp.setResultDesc(attentionTrainer.getId());
            }
        } catch (Exception e) {
            resp.setResult("false");
            resp.setResultDesc("新增出错!");
        }
        
        return resp;
    }
    
    /**
     * 
     * @Title: deleteAttention 
     * @Description: 取消关注
     * @param @param params
     * @param @param request
     * @param @return
     * @return MessageResp
     * @throws
     */
    @RequestMapping("deleteAttention")
    @ResponseBody
    public MessageResp deleteAttention(AttentionTrainerQueryParam params, HttpServletRequest request) {
        MessageResp resp = new MessageResp();
        
        User u = SessionUtils.getUser(request.getSession());
        //params.setUserId(u.getUserId());
        params.setUserId(SessionUtils.getEmpId(request.getSession()));
        
        try {
            if (attentionTrainerService.deleteAttention(params) > 0) {
                resp.setResult("true");
                resp.setResultDesc("取消关注成功!");
            }
            
        } catch (Exception e) {
            resp.setResult("false");
            resp.setResultDesc("删除出错!");
        }
        return resp;
    }
    
    /**
     * 
     * @Title: queryAttentionList 
     * @Description: 查询某讲师所有关注信息 
     * @param @param request
     * @param @param params
     * @param @return
     * @return Data
     * @throws
     */
    @RequestMapping("queryAttentionList")
    @ResponseBody
    public Data queryAttentionList(HttpServletRequest request, AttentionTrainerQueryParam params) {
        //User u = SessionUtils.getUser(request.getSession());
        
        PageBean pageBean = params.getPageBean();
        int count = attentionTrainerService.selectAttentionCount(params);// 查询某讲师所有关注信息 总数
        pageBean.setPageCount(String.valueOf(count));// 总页数
        
        Data data = new Data(pageBean);
        int offSet = PageUtil.setParameter(count, params.getPageBean());
        RowBounds row = new RowBounds(offSet, Integer.valueOf(params.getPageBean().getPageSize()));
        List<AttentionTrainerResp> list = attentionTrainerService.selectAttentionList(params, row); //查询某讲师所有关注信息 
        
        data.setBeans(list);

        return data;
    }
    
    /**
     * 
     * @Title: uploadHeadImg 
     * @Description: 上传头像 
     * @param @param file
     * @param @param xCoordinate
     * @param @param yCoordinate
     * @param @param width
     * @param @param imgName
     * @param @param height
     * @param @param request
     * @param @param model
     * @param @return
     * @return String
     * @throws
     */
    @RequestMapping(value = "/uploadHeadImg", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String uploadHeadImg(@RequestParam(value = "img", required = false) MultipartFile file,
            @RequestParam(value = "xCoordinate", required = false) Integer xCoordinate,
            @RequestParam(value = "yCoordinate", required = false) Integer yCoordinate,
            @RequestParam(value = "width", required = false) Integer width,
            @RequestParam(value = "imgName", required = false) String imgName,
            @RequestParam(value = "height", required = false) Integer height, HttpServletRequest request, ModelMap model) {
        
        String result = "";
        EmpMessageRes msg = new EmpMessageRes();
        
        //获得工程下面upload资源包路径,当然这个包是已经存在的了
        String path = request.getSession().getServletContext().getRealPath("upload/trainer_picture");
        
        //上传的图片的名称
        String fileName = file.getOriginalFilename();
        String newfileName = UUIDUtil.generateGUID() + fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        
        //下面是upload路径盘符的转化        
        StringBuffer importPath = new StringBuffer();
        String temp[] = path.split("\\\\");
        
        for (int i = 0; i < temp.length; i++) {
            importPath.append(temp[i]);
            importPath.append("/");
        }
        
        importPath.append(newfileName);
        //看是否存在upload包,没有则会新建一个upload包,作为资源上传的路径
        File targetFile = new File(path, newfileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        
        try { //文件上传
            file.transferTo(targetFile);
            /**
             *利用工具类对图片进行裁剪
             */
            //String name = "D:\\image.jpg";
            if (xCoordinate != null && yCoordinate != null && width != null && height != null) {
                OperateImage o = new OperateImage(xCoordinate, yCoordinate, width, height);
                o.setSrcpath(importPath.toString());
                o.setSubpath(importPath.toString());
                File toCompress = new File(importPath.toString());
                o.cut();
                if (toCompress.length() / 1024 > 50)
                    //将上传的图片进行压缩
                    ImgUtil.createIcon(importPath.toString());
            }
            msg.setResult("true");
            msg.setResultDesc("头像上传成功");
            msg.setImgUrl(newfileName);
            //result = "originalFilename=" + fileName + ";imgUrl=" + msg.getImgUrl() + ";result=" + msg.getResult() + ";resultDesc=" + msg.getResultDesc();
            
            result = msg.getImgUrl();
                    
        } catch (Exception e) {
            msg.setResult("false");
            msg.setResultDesc("头像上传失败");
            e.printStackTrace();
        }
        if (imgName != null) {
            File later = new File(path, imgName);
            if (later != null)
                later.delete();
        }
        
        return result;
    }

    
    
    
    
    
}
View Code


二、JS提交json串到后台:

JSP:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<title>新增课程</title>
<link href="${ctx}/static/images/common/logoicond.ico" rel="Shortcut Icon">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/common/dialog.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/common/alert.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/common/jquery.validator.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/elearning/common.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/elearning/course.css">
<link rel="stylesheet" type="text/css" href="${ctx}/static/css/elearning/xpTable.css">
<link rel="stylesheet" href="http://at.alicdn.com/t/font_1418873121_51064.css" type="text/css"> 
<link rel="stylesheet" href="http://at.alicdn.com/t/font_1425542799_1788247.css" type="text/css"> 
</head>
<body>
    <!--头部-->   
    <%@include file= "../../common/header.jsp"%>
    <script type="text/javascript" src="${ctx}/tools/uploadswf/upload.js"></script>
    <script type="text/javascript" src="${ctx}/static/js/common/window.js"></script>
    <script type="text/javascript" src="${ctx}/static/js/common/alert.js"></script>
    <script type="text/javascript" src="${ctx}/static/js/elearning/jquery.SuperSlide.2.1.1.js"></script>
    <script type="text/javascript" src="${ctx}/static/js/common/jquery.validator.js"></script>
    <script type="text/javascript" src="${ctx}/static/js/common/zh_CN.js"></script>
    <script type="text/javascript">
    
        $(function(){
            
            if($("#courseId").val()!="null"){
                $(".pagetitle").html("修改课程");
                var param = {id:$("#courseId").val()}
                $.ajax({
                    url: "${ctx}/td/course/view.do",
                    data: param,
                    success: function(data){
                        if(data.resources.length!=0){
                            var html;
                            for(var i=0; i<data.resources.length;i++){
                                html += "<tr class='done' data-resource_name='"+data.resources[i].resource_name+"' data-id='"+data.resources[i].id+"' data-resource_type='"+data.resources[i].resource_type+"'><td><input class='input-text name' type='text' name='name-"+data.resources[i].resource_title+"' value='"+data.resources[i].resource_title+"' data-rule='required;' /></td><td><input class='input-text period' type='text' data-rule='required;' value='"+data.resources[i].period+"' name='period-"+i+"' /></td><td><p><span class='filename' title='"+data.resources[i].resource_title+"'>"+data.resources[i].resource_title+"</span></p></td><td><p>已上传</p></td><td><span class='btn-sort iconfont' onclick='shiftUp(this);'>&#xe68c;</span><span class='btn-sort iconfont' onclick='shiftDown(this);'>&#xe68b;</span><span class='btn-del' onclick='del(this);'>删除</span></td></tr>";
                            }
                            $("#filelist").append(html);
                        }else{
                            
                        }
                    }
                });
            }
            
            $("#courseFileList").validator({
                timely:false,
                  focusInvalid:false,
                  focusCleanup:true,
                  showOk:false,
                valid: function(form){
                    //表单验证通过,提交表单到服务器
                    var itemjson ={id:$("#courseId").val(),resources:[]};
                    var i = 0;
                    if($("#filelist").find(".done").length!=0){
                         $("#filelist").find(".done").each(function(){
                            var arr = {
                                "id":$(this).attr("data-id"),
                                "resource_title":$(this).find(".name").val(),
                                "period":$(this).find(".period").val(),
                                 "sort_index":i
                            }
                            i++;
                            itemjson.resources.push(arr);
                        });
                        var param = {itemjson:JSON.stringify(itemjson)};
                        $.ajax({
                            url: "${ctx}/td/course/update.do",
                            type:"get",
                            data: param,
                            success: function(data){
                                if(data.result=="true"){
                                    //跳转到列表页
                                    location.href = "${ctx}/views/elearning/course/courseList.jsp";
                                }else{
                                    new AlertWin().initfn({
                                        "tipscon":data.resultDesc,
                                        "showtime":2000
                                    });
                                }
                            }
                        });
                    }else{
                        new AlertWin().initfn({
                            "tipscon":"课件不能为空,无法保存!",
                            "showtime":2000
                        });
                    }
                }
            });
            
            //上一步
            $("#addCancel").click(function(){
                location.href = "${ctx}/views/elearning/course/addcourse_step1.jsp?id="+$("#courseId").val();
            });
        });
        
        //删除标签
        function removeTag(obj){
            $(obj).parent().remove();
        }
        
        //上移一个
        function shiftUp(obj){
            var index = $(obj).parents("tr").index();
            var parentTr = $(obj).parents("tr"); 
            var prevTr = parentTr.prev(); 
            if(prevTr.length > 0){
                prevTr.insertAfter(parentTr); 
            }else{
                new AlertWin().initfn({
                    "tipscon":"已经到第一个了!",
                    "showtime":2000
                });
            }
        }
        
        //下移一个
        function shiftDown(obj){
            var index = $(obj).parents("tr").index();
            var parentTr = $(obj).parents("tr"); 
            var nextTr = parentTr.next(); 
            if(nextTr.length > 0){
                nextTr.insertBefore(parentTr); 
            }else{
                new AlertWin().initfn({
                    "tipscon":"已经到最后一个了!",
                    "showtime":2000
                });
            }
        }
        
        //取消文件
        function cancel(obj){
            var fileindex = $(obj).parents("tr").attr("data-fileindex");
            getMovie("swfid").cancelHandler(fileindex);
            $(obj).parents("tr").remove();
        }
        
        //删除文件
        function del(obj){
            var fileId = $(obj).parents("tr").attr("data-id");
            var param = {id:fileId}
            $.ajax({
                url: "${ctx}/td/resource/delete.do",
                type:"get",
                data: param,
                success: function(data){
                    if(data.result=="true"){
                        
                        $(obj).parents("tr").remove();
                        
                        new AlertWin().initfn({
                            "tipscon":data.resultDesc,
                            "showtime":2000
                        });
                    }else{
                        new AlertWin().initfn({
                            "tipscon":data.resultDesc,
                            "showtime":2000
                        });
                    }
                    
                }
            });
        }
        
        //展示文件列表
        function showfilelist(filelist){
        
            var list=filelist;
            var filelist=document.getElementById("filelist");
            var filelistDom = $("#filelist");
            for(var i=0;i<list.length;i++){
                 var filelabel=list[i].name;
                var filesize=(list[i].size/(1024*1024)).toFixed(2)+"MB";
                
                //文件信息
                var filediv=document.createElement("div");
                filediv.id="main-"+list[i].fileindex;
                var index = $("#filelist").find("tr").length;
                var fileHtml = "<tr id='main-"+list[i].fileindex+"' data-fileindex='"+list[i].fileindex+"'><td><input class='input-text name' type='text' name='name-"+index+"' value='"+filelabel+"' data-rule='required;' /></td><td><input class='input-text period' type='text' data-rule='required;'  name='period-"+index+"' /></td><td><p><span class='filename' title='"+filelabel+"'>"+filelabel+"</span></p></td><td class='processframe' id='processframe-"+list[i].fileindex+"'></td><td><span class='btn-sort iconfont' onclick='shiftUp(this);'>&#xe68c;</span><span class='btn-sort iconfont' onclick='shiftDown(this);'>&#xe68b;</span><span class='btn-cancel' onclick='cancel(this);'>取消</span><span class='btn-del hidden' onclick='del(this);'>删除</span></td></tr>";
                filelistDom.append(fileHtml);
                
                
                //进度条
                var fileprocessframe=document.createElement("div");
                fileprocessframe.id="process-"+list[i].fileindex;
                fileprocessframe.style.height="20px";
                fileprocessframe.style.width="200px";
                fileprocessframe.style.border="1";
                fileprocessframe.style.position="relative";
                //filelist.appendChild(fileprocessframe);
                filelistDom.find("td[id='processframe-"+list[i].fileindex+"']").append(fileprocessframe);
                
                var fileprocess=document.createElement("div");
                fileprocess.style.height="100%";
                fileprocess.style.width="0%";
                fileprocess.style.background="#d4e4ff";
                //fileprocess.style.position="absolute";
                fileprocess.id="bar-"+list[i].fileindex;
                fileprocessframe.appendChild(fileprocess);
                
                var filepercent=document.createElement("div");
                filepercent.innerHTML="0%";
                filepercent.style.position="absolute";
                filepercent.style.top="0px";
                filepercent.style.left="0px";
                filepercent.id="per-"+list[i].fileindex;
                //filepercent.id=list[i].fileindex;
                fileprocessframe.appendChild(filepercent);    
        
            }
            
        }
        
        function singleprocess(fileindex,process){
            document.getElementById("bar-"+fileindex).style.width=Math.round(process*100)+"%";
            document.getElementById("per-"+fileindex).innerHTML=Math.round(process*100)+"%";
            //document.getElementById("singleprocess").innerHTML=process;
        }
        function allprocess(process,totalsize){
            document.getElementById("allprocess").innerHTML="总共:"+(totalsize/(1024*1024)).toFixed(2)+"M,已处理:"+Math.round(process*100)+"%";
        }
        
        //上传完成
        function responsedata(fileindex,data){
            var json = eval('(' + data + ')'); 
            if(json.result=="true"){
                $("#filelist").find("tr[id='main-"+fileindex+"']").attr("data-resource_name",json.resource_name).attr("data-id",json.id).attr("data-resource_type",json.resource_type).addClass("done");
                $("#filelist").find("tr[id='main-"+fileindex+"']").find(".btn-cancel").addClass("hidden");
                $("#filelist").find("tr[id='main-"+fileindex+"']").find(".btn-del").removeClass("hidden");
                $("#filelist").find("tr[id='main-"+fileindex+"']").find(".processframe").html("<p>已上传</p>");
            }
        }
        function showTip(tip){
            alert(tip);
        }
        
        window.onload=function(){
            swfObject(
                    "swfid",
                    "addFile",
                    "<%=basePath%>tools/uploadswf/FlashUploadList.swf",
                    {
                        width:141,
                        height:46,
                        browseimage:"${ctx}/static/images/elearning/btn-upload.png"
                    },
                    {
                    upload_url :"<%=basePath%>td/resource/upload?course_id=saveDataId1",
                    //upload_maxfile:10,
                    upload_maxcount:4,
                    //buttontext:"上传附件",
                    singleProcess:"singleprocess",
                    //allProcess:"allprocess",
                    onResponse:"responsedata"
                    //onIOError:"showTip"
                });
        }
    </script>
    <!--头部  -->
    <div class="study_bar clearfix">
         <div class="bd">
            <div class="studytitle">课程管理</div>
            <div class="search">
                <input class="input_text" type="search" placeholder="搜索在线学习教程"/>
                <i class="iconfont">&#xe605;</i>
                <button class="searchbtn">搜索</button>
                <a class="link" href="#">全部课程</a>
            </div>
            <div class="clearfix"></div>
            <ol class="breadcrumb">
                <li><i class="iconfont index">&#xe672;</i><a href="${ctx}/emp/index.do">管理与服务</a></li>
                <li><i class="iconfont">&#xe622;</i><a>培训与管理</a></li>
                <li><i class="iconfont">&#xe622;</i><a>课程管理</a></li>
            </ol>
        </div>
   </div>
       <!--内容开始  -->
   <div class="bd">
        <div class="addcourese">
                <div class="title">
                    <i class="iconfont">&#58929</i>
                    <span class="pagetitle">新增课程</span>
                </div>
                <div class="slideSetBox clearfix">
                    <div class="hd">
                        <ul>
                            <li><a>第一步:基本信息</a></li>
                            <li class="on"><a>第二步:课程大纲</a></li>
                        </ul>
                    </div>
                    <div class="bd">
                        <ul>
                            <li class="clearfix">
                                <div class="courseOutline">
                                    <div class="addOutline">
                                        请增加课程目录:<a id="addFile"></a>
                                    </div>
                                    <form id='courseFileList'>
                                        <div class="clearfix">
                                            <table class="table">
                                                <thead>
                                                    <tr>
                                                        <th width="180">课程目录</th>
                                                        <th width="100">学时</th>
                                                        <th width="300">对应课件</th>
                                                        <th>上传进度</th>
                                                        <th width="200">操作</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="filelist">
                                                </tbody>
                                            </table>
                                        </div>
                                        <div class="clearfix" style="text-align: right; margin-top:30px;">
                                            <button id="addCancel" type="button" class="btn btn-default btn-lg">上一步</button>&nbsp; &nbsp; &nbsp;
                                            <button type="submit" class="btn btn-info btn-lg">保存并完成</button>
                                        </div>
                                    </form>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
        </div>
    </div>
    <div style="display: none;">整体进度:<span id="allprocess"></span></div>
    <input type="hidden" id="courseId" value="<%=request.getParameter("id")%>" />
</body>
</html>
View Code

 

后台:

@RequestMapping("update")
    @ResponseBody
    public MessageResp updateCourse(String itemjson, HttpSession session) {
        User user = SessionUtils.getUser(session);
        String resultdesc="更新成功";
        String result="true";
        CourseQueryParam param;
        ObjectMapper mapper = new ObjectMapper();
        
        try{
            param = mapper.readValue(itemjson,CourseQueryParam.class);//Json对象转为实体对象
            List<ResourceQueryParam> resources = param.getResources();
            
            courseService.updateCourse(user, param);
        }catch(Exception e){
            resultdesc=e.getMessage();
            result="false";
            log.error("更新课程错误", e);
        }
        return this.newMessageResp(result, resultdesc);
    }
View Code
package com.dayhr.web.module.hr.td.elearn.param;

import java.util.ArrayList;
import java.util.List;
import com.dayhr.web.module.hr.td.elearn.param.ResourceQueryParam;
import com.dayhr.web.platform.pagination.PageBean;


public class CourseQueryParam {
    
    private String id;
    private String name;
    private String course_id;
    private String description;
    private Integer online;
    private Integer originality;
    private String labels;//课程标签组
    
    private String author;
    private Double period;
    private Double learning_credit;//学习得分
    private Double teaching_credit;//讲授得分
    private String memo;
    private Integer total_resource;
    private Double total_period;
    private Double total_credit;
    private String cover;
    
    private String for_target;//适用人群
    private Integer audit;//审核人
    
    
    private List<ResourceQueryParam> resources = new ArrayList<ResourceQueryParam>();//课程资源
    
    
    //专为查询新增的属性
    private String label;//课程标签
    private Integer level;//所属课程类型层级
    
    private Integer maxLabelCount=5;//查询列表top最多展示的页签个数
    
    /**
     * 分页工具
     */
    private PageBean pageBean;
    
    
    get()、set()方法。。。。
    
    
}
View Code
package com.dayhr.web.module.hr.td.elearn.param;

import com.dayhr.web.platform.pagination.PageBean;

public class ResourceQueryParam {
    private String id;
    private String resource_title;//资源标题
    private String resource_name;
    private Integer resource_type;//资源类型
    private String url;
    private Double period;
    private Double credit;
    private Integer sort_index;
    private Integer ismain;
    private String course_id;
    private Integer convert_state;
    private String convert_frame;//转换帧
    /**
     * 分页工具
     */
    private PageBean pageBean;
    
        get()、set()方法。。。
    
    
}
View Code

 

posted @ 2015-03-20 10:03  mingyue1818  阅读(329)  评论(0编辑  收藏  举报