1、表格樣式:javascript
JSP:css
<%@ 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> </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> </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:""},{btnName:"修改",btnfn:editTeacher,className:"btn btn-default",icon:""},{btnName:"禁用 ",btnfn:delTeacher,className:"btn btn-default",icon:""},{btnName:"啓用 ",btnfn:enableTeacher,className:"btn btn-default",icon:""}] }) ] }); 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'></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)'></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'></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'></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)'></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)'></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)'></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"></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"></i><a href="${ctx}/emp/index.do">管理與服務</a></li> <li><i class="iconfont"></i><a href="${ctx}/emp/index.do#pxhd">培訓管理</a></li> <li><i class="iconfont"></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> </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'></i>添加標籤</a> <div class="taginput clearfix"> <input class="form-control" id="tagName" type="text" /> <i class="iconfont ok" id="addtag-ok"></i> <i class="iconfont cancel" id="addtag-cancel"></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>
禁止按回車鍵提交表單:在form標籤中加入: onkeydown="if(event.keyCode==13)return false;"html
<form id="formId" method="post" enctype="multipart/form-data" onkeydown="if(event.keyCode==13)return false;" >前端
</form>java
後臺:jquery
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; } }
2、JS提交json串到後臺:web
JSP:ajax
<%@ 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);'></span><span class='btn-sort iconfont' onclick='shiftDown(this);'></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);'></span><span class='btn-sort iconfont' onclick='shiftDown(this);'></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"></i> <button class="searchbtn">搜索</button> <a class="link" href="#">所有課程</a> </div> <div class="clearfix"></div> <ol class="breadcrumb"> <li><i class="iconfont index"></i><a href="${ctx}/emp/index.do">管理與服務</a></li> <li><i class="iconfont"></i><a>培訓與管理</a></li> <li><i class="iconfont"></i><a>課程管理</a></li> </ol> </div> </div> <!--內容開始 --> <div class="bd"> <div class="addcourese"> <div class="title"> <i class="iconfont"></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> <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>
後臺:spring
@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); }
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()方法。。。。 }
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()方法。。。 }