------------------addUser.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.ibeifeng.po.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
List<Role> roleList = (List<Role>) request.getAttribute("rolelist");
if (roleList == null) {
response.sendRedirect("findAllRoleAction.action");
return;
}
Set<String> resource = (Set<String>) session
.getAttribute("resource");
if (!resource.contains("4_1")) {
response.sendRedirect(basePath + "admin/login.jsp");
return;
} else {
}
String alertInfo = (String)request.getAttribute("alertInfo");
if (alertInfo == null) {
alertInfo = "";
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><%=Title.TITLE%></title>
<link type="text/css" rel="stylesheet"
href="/style/admin/index/backhead.css" />
<link type="text/css" rel="stylesheet"
href="/style/admin/user/user.css" />
<link type="text/css" rel="stylesheet"
href="<%=basePath%>style/admin/admin_question_questionCtl_addQsn.css">
<script language="javascript" charset="UTF-8" src="<%=basePath %>js/jquery.js"></script>
<!-- 使用的是 ajaxfileupload 上传插件; -->
<script language="javascript" charset="UTF-8" src="<%=basePath %>js/ajaxfileupload.js"></script>
<script language="javascript" charset="UTF-8"
src="/include/Of/LanguagePacks/L.js">
</script>
<script type="text/javascript">
function ajaxFileUpload()
{
$("#loading")
.ajaxStart(function(){
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function(){
$(this).hide();
});//文件上传完成将图片隐藏起来
$.ajaxFileUpload
(
{
url:'fileUploadAction.action',//用于文件上传的服务器端请求地址
secureuri:false,//一般设置为false
fileElementId:'file',//文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'json',//返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量
window.clearInterval(int);// 停止计时器; int 是计时器; 名字有点怪;
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
clearInterval(int);// 停止计时器; int 是计时器; 名字有点怪;
}else
{
alert(data.message);
clearInterval(int);// 停止计时器; int 是计时器; 名字有点怪;
}
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
clearInterval(int);// 停止计时器; int 是计时器; 名字有点怪;
}
}
)
return false;
}
</script>
<script>
window.onload = function() {
var alertInfo='<%=alertInfo%>';
if(alertInfo!=null&&alertInfo!=""&&alertInfo!=undefined){
alert(alertInfo);
}
}
function clock()
{
// var t=new Date().toLocaleString();
var t="";
// 防止 ie 缓存;
var datatime=new Date().getTime();
$.ajax({
type: 'post',
url: '<%=basePath%>findUploadSuccessNumberAction.action',
data: {
// roleid:selectedroleid
time:datatime
},
dataType: 'json',
success: function (data) {
if(data.successNum==null||data.successNum=="undefined"||data.successNum=="null"){
}else{
document.getElementById("clock").value="上传数量:"+data.successNum ;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
try {
if (p.onError) p.onError(XMLHttpRequest, textStatus, errorThrown);
} catch (e) {}
}
});
}
</script>
<script language="javascript" charset="UTF-8">
if (typeof window.L === 'object' && typeof window.L.init === 'function') {
window._ROOT_URL = window.L._rootUrl = '';
window.L._adminUrl = '/admin' || undefined;
window.L.init( [], '');
}
if (!window.L.extension.jsErrorLog) {
window.L.extension.jsErrorLog = true;
window.onerror = function(message, file, line) {
file = file.substr(file.indexOf(window.L._rootUrl, 7)
+ window.L._rootUrl.length);
window.L.AJAX( {
url : window.L._rootUrl + '/include/Of/Log/writeJsLog.php',
async : true,
data : window.L.param.encode( {
'message' : message,
'file' : file,
'line' : line
}),
type : 'post'
});
}
}
</script>
</head>
<body>
<link href="../favicon.ico" rel="shortcut icon">
</head>
<body>
<style>
.warning {
border: red 1px solid;
background: #FCC
}
.hand {
cursor: pointer;
}
</style>
<div class="box block_11">
<!-- // block_## 序号对应全局的颜色定义 -->
<div class="box_inner">
<!-- // 顶部 -->
<div class="header">
<jsp:include page="../top.jsp" />
<div class="nav">
<span>用户/组织/权限</span>
<ul>
<li>
<a class='ihover'
style="<%=resource.contains("4_1") ? "" : "display:none"%>"
href="<%=basePath%>admin/user/addUser.jsp"> 添加用户</a>
</li>
<li>
<a class=''
style="<%=resource.contains("4_2") ? "" : "display:none"%>"
href="<%=basePath%>admin/user/userManager.jsp"> 用户管理</a>
</li>
<li>
<a class=''
style="<%=resource.contains("4_3") ? "" : "display:none"%>"
href="<%=basePath%>admin/group/organise.jsp"> 组织管理</a>
</li>
<li>
<a class=''
style="<%=resource.contains("4_4") ? "" : "display:none"%>"
href="<%=basePath%>admin/role/roleManage.jsp"> 角色管理</a>
</li>
</ul>
</div>
</div>
<!-- // 用户资料 -->
<div class="panel_1 con_input">
<div class="title">
<span>用户资料</span>
</div>
<div class="content">
<form action="www.baidu.com" id="user_form"></form>
<div class="col_left" style="width: 50%;">
<script>
function showUserGroup() {
var option = {
'targetId' : 'select_target_name',
'targetNameId' : 'group_name',
'targetValueId' : 'group',
'dataType' : 'group',
'isCheckBox' : false,
'showRoot' : false,
'allowCheckParent' : true,//是否允许选择父菜单
'expandLevel' : 2
};
getTree(option);
}
function test() {
alert(document.getElementById('group').value)
}
function testupload(){
// 启动定时器 int 是定时器;起的 名字有点怪; 全局变量; 否则不管用; 不加上var;
int=self.setInterval("clock()",50)
return ajaxFileUpload();
}
function afterSumbmit(msg) {
alert(msg);
}
function checkNumbernew(o) {
o.value = o.value.replace(/[^\d]/g, '');
o.value = Number(o.value);
if (o.value >= 2147483647) {
o.value = 2147483646;//integer.maxvalue;
}
}
function checkNumber(s) {
var patrn = /^[0-9]{1,20}$/;
if (!patrn.exec(s)) {
return false;
} else {
return true
}
}
function importExcel(){
var msg = "人员过多时会花费系统较长时间,在点击导入按钮后请安心等待,不要做其他操作,您确认要执行导入吗?";
if (confirm(msg)==true){
var form=document.getElementById("importForm11");
form.submit();
}
}
function checkFormNew(){
// var pwd = document.getElementById('pwd');
// var repwd = document.getElementById('repwd');
var real_name = document.getElementById('real_name');
var employeeNumber = document.getElementById('employeeNumber');
var workNumber = document.getElementById('workNumber');
var group_name = document.getElementById('group_name');
var identy = document.getElementById('identy');
var banZu = document.getElementById('banZu');
var gongZuoZhengBianHao = document.getElementById('gongZuoZhengBianHao');
// var age = document.getElementById('age');
if(group_name.value==""){
alert("请选择所属组织");
return ;
}
if(banZu.value==""){
alert("班组不能为空");
return ;
}
if(real_name.value==""){
alert("真实姓名不能为空");
return ;
}
if(employeeNumber.value==""){
// alert("员工编号不能为空");
alert("工号不能为空");
return ;
}else{
}
// if(age.value!=""&&!checkNumber(age.value)){
// alert("年龄只能是数字");
//
//
// return ;
//
// }
if(workNumber.value==""){
alert("工作证号不能为空");
return ;
}if(gongZuoZhengBianHao.value==""){
alert("工作证编号不能为空");
return ;
}
if(workNumber.value!=""&&!checkNumber(workNumber.value)){
alert("工作证号只能是数字");
return ;
}
if(identy.value==""){
alert("身份证号不能为空");
return ;
}
// if (pwd.value == repwd.value&&(pwd.value!="")) {
//
// } else {
// alert("密码不能为空并且两次密码须一致");
// return ;
// }
document.getElementById('myform').submit();
clsSubmitForm();// clearup
}
</script>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<colgroup>
<col style="width: 90px;" />
<col style="" />
</colgroup>
<form action="addEmployeeAction.action" method='post'
target='hiddenifr' id="myform">
<tr>
<td style="color: red;">
必填项:
</td>
<td>
</td>
</tr>
<tr>
<td>
所属部门:
</td>
<td>
<input class="input1 auto_width hand" type="text"
name="group_name" id="group_name" readonly
onClick="showUserGroup()" />
<input type="hidden" id="group" name="groupid" />
</td>
</tr>
<tr>
<td>
员工姓名:
</td>
<td>
<input class="input3 auto_width" type="text"
name="real_name" id="real_name" />
</td>
</tr>
<!-- -->
<!-- <tr>-->
<!-- <td>-->
<!-- 密码:-->
<!-- </td>-->
<!-- <td>-->
<!-- <input class="input3 auto_width" type="password" name="pwd"-->
<!-- id="pwd" />-->
<!-- </td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>-->
<!-- 确认密码:-->
<!-- </td>-->
<!-- <td>-->
<!-- <input class="input3 auto_width" type="password" name="repwd"-->
<!-- id="repwd" />-->
<!-- </td>-->
<!-- </tr>-->
<!--
<!--
<tr>
<td>
是否管理员:
</td>
<td>
<label class="hand">
<input class="radiobox" name="isadmin" type="radio"
value="0" checked="checked" onClick="hiddDiv()" />
否
</label>
<label class="hand">
<input class="radiobox" name="isadmin" type="radio"
value="1" onClick="adminPanel()"
style="padding-left: 35px;" />
是
</label>
</td>
</tr> -->
<tr>
<td>
工作证号:
</td>
<td>
<input class="input3 auto_width" type="text"
name="workNumber" id="workNumber" />
</td>
</tr>
<tr>
<td>
工作证编号:
</td>
<td>
<input class="input3 auto_width" type="text"
name="gongZuoZhengBianHao" id="gongZuoZhengBianHao" />
</td>
</tr>
<tr>
<td>
工号:
</td>
<td>
<input class="input3 auto_width" name="employeeNumber"
type="text" id="employeeNumber" />
</td>
</tr>
<tr>
<td>
身份证号:
</td>
<td>
<input class="input1 auto_width" type="text" name="identy"
id="identy" />
</td>
</tr>
<tr>
<td>
角色:
</td>
<td>
<select class="select3 ~auto_width" id="roleId"
name="roleId" οnchange="">
<!-- paprTypeChange() -->
<%
for (int i = 0; i < roleList.size(); i++) {
if (i == 0) {
%>
<option value="<%=roleList.get(i).getId()%>"
selected="selected"><%=roleList.get(i).getRoleName()%></option>
<%
} else {
%>
<option value="<%=roleList.get(i).getId()%>"><%=roleList.get(i).getRoleName()%></option>
<%
}
}
%>
</select>
</td>
</tr>
<tr>
<td>
工种:
</td>
<td>
<select class="select3 ~auto_width" id="workType"
name="workType" οnchange="">
<!-- paprTypeChange() -->
<%
List<String> workTypeList = (List<String>) session
.getAttribute("workTypeList");
if (workTypeList != null) {
for (int i = 0; i < workTypeList.size(); i++) {
if (i == 0) {
%>
<option value="<%=workTypeList.get(i)%>"
selected="selected"><%=workTypeList.get(i)%></option>
<%
} else {
%>
<option value="<%=workTypeList.get(i)%>"><%=workTypeList.get(i)%></option>
<%
}
}
}
%>
</select>
</td>
</tr>
</table>
</div>
<div class="col_right">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<colgroup>
<col style="width: 110px;" />
<col style="" />
</colgroup>
<tr>
<td style=" color: red;">
.
</td>
<td>
</td>
</tr>
<tr>
<td>
班组:
</td>
<td>
<input class="input1 auto_width" type="text" name="banZu"
id="banZu" />
</td>
</tr>
<!-- <tr >-->
<!-- <td>-->
<!-- 电话:-->
<!-- </td>-->
<!-- <td>-->
<!-- <input class="input3 auto_width" type="text" name="telphone"-->
<!-- id="telphone" -->
<!-- />-->
<!-- </td>-->
<!-- </tr>-->
<!-- <tr>-->
<!-- <td>-->
<!-- E-mail:-->
<!-- </td>-->
<!-- <td>-->
<!-- <input class="input3 auto_width" type="text" name="email"-->
<!-- id="email" />-->
<!-- </td>-->
<!-- </tr>-->
<tr>
<td>
出生日期:
</td>
<td>
<input class="input3 auto_width" name="birthday" type="text"
id="birthday" readonly />
</td>
</tr>
<tr>
<td>
性别:
</td>
<td>
<label>
<input class="radiobox" type="radio" name="gender" value="1"
id="gender1" checked />
</label>
<label for="gender1" class="hand">
男
</label>
<label class="hand">
<input class="radiobox" type="radio" name="gender" value="0"
style="padding-left: 31px;" />
女
</label>
</td>
</tr>
<tr>
<td colspan="2">
<div id="adminView"></div>
<input type="hidden" id="adminGroup" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="role" style="display: none">
<span style="margin-left: 30px;"></span>
<input type="hidden" id="role_id" />
</div>
</td>
</tr>
<form />
</table>
</div>
</form>
</div>
</div>
<!--add 2012 11 28 <div class="clear"></div>-->
<div class="clear"></div>
<div class="panel_1 con_input">
<div class="title">
<span>上传用户excel</span>
</div>
<div class="content">
<input type="button" id="import_download" value="用户模板下载"
style="display: block; float: left; margin-left: 15px; margin-right: 2px; width: 130px"
class="btn"
οnclick="window.location='<%=basePath%>servlet/DownLoadServlet?path=../resource/ryb.xls'" />
<%-- <form action='<%=basePath%>servlet/FileUploadForUser'--%>
<%-- method='post' enctype='multipart/form-data' id="importForm11"--%>
<%-- target='frameFile11'>--%>
<%----%>
<%----%>
<%-- <input type="hidden" id='hiddenstoreid' name="storeid" value="" />--%>
<%-- <input type='file' name='upfile' id="fileinput"--%>
<%-- style="display: block; float: left; margin-right: 2px; width: 500px;"--%>
<%-- class="btn">--%>
<%-- <input type="button" id="import" value="导入用户"--%>
<%-- οnclick="importExcel()"--%>
<%-- style="display: block; float: left; margin-right: 2px; width: 80px"--%>
<%-- class="btn" />--%>
<%-- </form>--%>
<%----%>
<%-- <iframe id='frameFile11' name='frameFile11'--%>
<%-- style='display: none;'></iframe>--%>
<img src="loading.gif" id="loading" style="display: none;">
<%-- <input type="file" id="file" name="file" />--%>
<input type='file' id="file" name="file"
style="display: block; float: left; margin-right: 2px; width: 500px;"
class="btn">
<input type="button" value="上传" style="display: block; float: left; margin-right: 2px; width: 80px" class="btn" οnclick="testupload()">
<input type="text" id="clock" size="35" />
</div>
</div>
<div class="clear"></div>
<iframe style="display: none" name="hiddenifr"></iframe>
<!-- // 主按钮区(分左中右) -->
<div class="button_area_search">
<%-- <div class="center">--%>
<%-- <a href="#" class="btn" id="save" οnclick="javascript:document.getElementById('myform').submit()">保 存</a>--%>
<%-- <a href="#" class="btn" onClick="test()" >清 空</a>--%>
<%-- </div>--%>
<a href="#" class="btn" onClick="checkFormNew();return false;">保 存</a>
<a href="#" class="btn" onClick="clsSubmitForm();return false;">清 空</a>
<a href="<%=basePath%>admin/index.jsp" class="btn" onClick="">返 回</a>
</div>
<!-- // footer -->
<%-- <div id="footer"><a href="http://www.orivon.com" target="_blank">Powered by Orivon</a></div>--%>
<jsp:include page="../footer.jsp" />
</div>
<!-- // box_inner end -->
</div>
<!-- // box end -->
<script>
function uploadSuccess(msg) {
alert(msg);
window.location = '/exam2/admin/user/addUser.jsp';
}
function isAdmin() {
var option = {
'targetId' : 'adminPanel',
'dataType' : 'group',
'isCheckBox' : false,
'showRoot' : false,
'isCheckBox' : true,
'callbackFn' : viewCon,
'expandLevel' : 2,
onCheck : treeOnCLick,
'chkboxType' : {
"Y" : "",
"N" : ""
}
};
getTree(option);
}
function treeOnCLick(event, treeId, treeNode) {
var dataObj = {
'id' : treeNode.id,
'name' : treeNode.name
}
if (treeNode.checked) {
viewCon(dataObj, 'a');
} else {
delGroupPanel(dataObj.id)
}
}
function adminPanel() {
$("#adminPanel").css('display', '');
$("#adminView").css("display", '');
$("#role").css("display", '');
}
function viewCon(dataObj, s) {
$("#adminView").css("display", '');
var text = ' 管 理 组 : ';
var spanStr = $("#adminView").html();
var spanId = $("#adminGroup").val();
if (spanStr.length == 0)
$("#adminView").html(text);
$("#adminView").append(
'<span id=gSpan_' + dataObj.id + '>' + dataObj.name
+ ' </span>');
$("#adminGroup").val(spanId + ',' + dataObj.id)
//<img src=# class=delImg onClick=delGroupPanel('+dataObj.id+')></img>
//$("#imgId").attr('src',L._rootUrl+'/images/icon/icon_del_normal.png');
//addDelClass();
}
//"权 限:"
function addRole(id, name) {
var oldName = $("#role span").html();
if (oldName.length == 0) {
$("#role").html(
"权 限:" + $("#role").html());
}
var chkS = $("#r_" + id).attr('checked') == 'checked' ? true : false;
var oldVal = $("#role_id").val();
if (chkS) {
$("#role").css('display', '');
var newName = '<span id="rp_' + id + '">' + name
+ '<img src=# class=delImg onClick=delSpan(' + id
+ ')></img></span>';
oldVal += (',' + id);
$("#role_id").val(oldVal);
$("#role span").html(oldName + ' ' + newName);
} else {
//删除节点,替换节点成空
var str = '<span +id=(\'|"|)rp_' + id + '\\1 *>.*?<\\/span>';
var expStr = eval('/' + str + '/ig');
var newName = oldName.replace(expStr, '');
$("#role span").html(newName);
var val = oldVal.substr(1);
var valArr = val.split(',');
var newVal = '';
for ( var t in valArr) {
if (valArr[t] != id) {
newVal += (',' + valArr[t]);
}
}
$("#role_id").val(newVal);
}
addDelClass();
}
function selRole() {
$("#rolePanel").css('display', '');
var obj = $("#adminPanel");
var objSet = obj.offset();
$("#rolePanel").css('left', (objSet.left + 80));
$("#rolePanel").css('top', objSet.top + 20);
$("#rolePanel").css('zIndex', '500');
$("body").bind('click', function() {
document.onmousemove = mouseMove;
});
return false;
}
function mouseMove(ev) {
var obj = $("#adminPanel");
var objSet = obj.offset();
ev = ev || window.event;
//$("#tel").val(x)
var x = ev.pageX;
var y = ev.pageY;
// ||
if ((x < (objSet.left + 80) || x > (objSet.left + 370))
|| (y < objSet.top || y > (objSet.top + 210)))
$('#rolePanel').css('display', 'none');
}
/*
function selRole()
{
var roleNameStr = '';
var roleId = '';
var obj = {'mouseClickFun':function(returnStatus,windowObj, callBack) {
if(returnStatus){
var divNum = callBack.handle;
var formObj = $(window.frames["oDialogDiv_iframe_"+divNum].document);
var tr = formObj.find('table tr');
tr.each(function()
{
var chk = $(this).find('input[name=uid]:checked').val();
if(chk > 0)
{
var name = $(this).find('td:eq(1)').html();
$("#role").css('display','');
roleNameStr += ('<span id=span_'+chk+'>'+name+'<img src=# class=delImg onClick=delSpan('+chk+')></img></span> ');
roleId += (','+chk);
}
})
$("#role span").html(roleNameStr);
$("#role_id").val(roleId);
addDelClass();
}
}}
window.L.openCom('oDialogDiv')("权限选择"
, 'iframe:./userCtl.php?a=adminPower'
, "460", "auto"
, [2,obj]);
return false;
}
*/
function addDelClass() {
$(".delImg").attr('src', L._rootUrl + '/images/icon/icon_del_normal.png');
$(".delImg").bind('mouseover', function() {
$(this).attr('src', L._rootUrl + '/images/icon/icon_del_over.png');
}).bind('mouseout', function() {
$(this).attr('src', L._rootUrl + '/images/icon/icon_del_normal.png');
})
}
function delSpan(id) {
var newRoleId = '';
$("#rp_" + id).remove();
var roleArr = $("#role_id").val().substr(1).split(",");
for ( var t in roleArr) {
if (roleArr[t] != id) {
newRoleId += (',' + roleArr[t]);
}
}
$("#r_" + id).attr('checked', false);
$("#role_id").val(newRoleId);
if ($("#role_id").val() == "") {
$("#role").css("display", 'none');
}
}
function delGroupPanel(id) {
var newGroupId = '';
$("#gSpan_" + id).remove();
var groupArr = $("#adminGroup").val().substr(1).split(",");
for ( var t in groupArr) {
if (groupArr[t] != id) {
newGroupId += (',' + groupArr[t]);
}
}
$("#adminGroup").val(newGroupId);
$("#treeListgrouptrue_1_check").attr('checked', false)
if ($("#adminGroup").val() == "") {
$("#adminView").css("display", 'none');
}
}
function hiddDiv() {
$('#adminPanel').css('display', 'none');
$('#adminView').css('display', 'none');
$('#role').css('display', 'none');
}
//验证准考证是否唯一
$("#examcard").blur(function() {
var examcard = $('#examcard').val();
if (examcard !== null || examcard !== "") {
var data = {
'examcard' : examcard
}
$.post("./userCtl.php?a=checkExamCard", data, function(returnData) {
if (returnData == '2') {
alert(window.L.getText('准考证111已存在'));
$("#isfalse").attr("name", "istrue");
$("#isfalse").attr("name", "isfalse");
} else {
$("#isfalse").attr("name", "isfalse");
}
})
}
})
</script>
</body>
</html>
<script language="javascript" charset="UTF-8"
src="/js/admin/songComm.js">
</script>
<script language="javascript" charset="UTF-8"
src="/js/admin/user/userAdd.js">
</script>
<script language="javascript" charset="UTF-8"
src="/exam2/js/admin/manyTreesForUser.js">
</script>
</body>
</html>
---------ajaxfileupload.js
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
if(window.ActiveXObject) {
// 最开始的时候是这样; 但是ie 不兼容; 改成下面的ok了;
// var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
var io = document.createElement("iframe");
io.id=frameId;
io.name=frameId;
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})
------struts 配置
<action name="fileUploadAction" class="employee">
<!-- 上传之后返回信息; ajax上传; -->
<result type="json" name="success">
<param name="contentType">
text/html
</param>
</result>
<result type="json" name="error">
<param name="contentType">
text/html
</param>
</result>
</action>
private Integer successNumer;
public String getSuccessUploadEmloyeeNumber() {
Integer successNum = (Integer) ServletActionContext.getRequest()
.getSession().getAttribute("successNumer");
this.successNumer = successNum;
return SUCCESS;
}
/**
* -文件上传 begin;
*/
// -----------
private File file;
private String fileFileName;
private String fileFileContentType;
private String message = "你已成功上传文件";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileFileContentType() {
return fileFileContentType;
}
public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
}
private List<String> workTypeList = new ArrayList<String>();// 用于盛放原来数据库没有的Employee
private Integer successNum;
public Integer getSuccessNum() {
return successNum;
}
public void setSuccessNum(Integer successNum) {
this.successNum = successNum;
}
public String findUploadSuccessNumber() {
this.successNum = (Integer) ServletActionContext.getRequest()
.getSession().getAttribute("successNumer");
if (successNum == null) {
successNum = 0;
}
return SUCCESS;
}
@SuppressWarnings("deprecation")
@Override
public String execute() throws Exception {
String path = ServletActionContext.getRequest().getRealPath("/upload");
try {
File f = this.getFile();
if (!this.getFileFileName().endsWith(".xls")
&& (!this.getFileFileName().endsWith(".XLS"))) {
message = "对不起,你上传的文件格式不允许!!!只能是.xls文件";
return ERROR;
}
// 上传代码;
// FileInputStream inputStream = new FileInputStream(f);
// FileOutputStream outputStream = new FileOutputStream(path + "/"+
// this.getFileFileName());
// byte[] buf = new byte[1024];
// int length = 0;
// while ((length = inputStream.read(buf)) != -1) {
// outputStream.write(buf, 0, length);
// }
// inputStream.close();
// outputStream.flush();
FileInputStream fin = new FileInputStream(f);
HSSFWorkbook work = new HSSFWorkbook(fin);
fin.close();// 不知道为什么关闭 但是测试是没问题的;
HSSFSheet sheet = work.getSheetAt(0);
int row = sheet.getLastRowNum() + 1;// 加1 否则会少一条;
// for (int rowIndex = 0; rowIndex <= row; rowIndex++) {
// // 时间,整形,字符串
// // 第一列 时间
// HSSFCell cell = sheet.getRow(rowIndex).getCell(0);
// String str7 = ReadExcelUtil.getStringByCell(cell).trim();
// System.out.println(str7);
//
// }
Integer successNum = 0;
;
List<String> msgList = new ArrayList<String>();
successNum = readDataFromExcel(msgList, sheet, row, null,
successNum, ServletActionContext.getRequest(),
ServletActionContext.getResponse());
System.out.println("size======" + successNum);
//
// message = "对不起,你上传的文件格式不允许!!!只能是.xls文件";
// return ERROR;
if (msgList != null && msgList.size() > 0) {
message = msgList.get(0);
return ERROR;
} else {
message = "导入成功,数量为:" + successNum;
}
} catch (Exception e) {
e.printStackTrace();
message = "对不起,文件上传失败了!!!!";
}
return SUCCESS;
}
private List<Employee> emplist = new ArrayList<Employee>();
private Integer readDataFromExcel(List<String> msgList, HSSFSheet sheet,
int rows, Store store, Integer successNumer,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DetachedCriteria worktypedc = DetachedCriteria.forClass(WType.class);
workTypeList = this.workTypeService.findByCriteria(0,
Integer.MAX_VALUE, worktypedc);
if (workTypeList == null || workTypeList.size() == 0) {
return 0;
}
DetachedCriteria empdc = DetachedCriteria.forClass(Employee.class);
emplist = (List<Employee>) this.employeeService.findByCriteria(0,
Integer.MAX_VALUE, empdc);
DetachedCriteria dc = DetachedCriteria.forClass(Organise.class);
List<Organise> organiseList = (List<Organise>) this.organiseService
.findByCriteria(0, Integer.MAX_VALUE, dc);
HSSFRow firstRow = sheet.getRow(0);
if (firstRow == null) {
msgList.add("第一行必须是标题且不能为空");
return 0;
}
Integer cellCount = 0;
if (firstRow != null) {
Integer cellLength = sheet.getRow(0).getPhysicalNumberOfCells();
for (int i = 0; i < cellLength; i++) {
String cellStr = ReadExcelUtil.getStringByCell(
firstRow.getCell(i)).trim();
if ("".equals(cellStr)) {
continue;
}
cellCount++;
System.out.println("title---begin");
System.out.print(i + cellStr + "\t");
System.out.println("title---end");
}
if (cellCount == null || (cellCount != 10)) {
msgList.add("列数不正确,根据模板要求,列数必须是10列");
return 0;
} else {
for (int i = 0; i < cellCount; i++) {
String cellStr = ReadExcelUtil.getStringByCell(
firstRow.getCell(i)).trim();
switch (i) {
case 0:
if (cellStr.indexOf("工号") >= 0) {
} else {
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是工号");
return 0;
}
break;
case 1:
if (cellStr.indexOf("车间") >= 0) {
} else {
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是车间");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
}
break;
case 2:
if (cellStr.indexOf("班组") >= 0) {
} else {
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是班组");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
}
break;
case 3:
if (cellStr.indexOf("姓名") >= 0) {
} else {
// titleList = new ArrayList<String>();
// msgList.add("表头不正确,请检查第1行第" + (i + 1) +
// "列");
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是姓名");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
}
break;
case 4:
if (cellStr.indexOf("性别") >= 0) {
} else {
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是性别");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
// throw new
// RuntimeException("表头不正确,请检查第1行第"
// + (i + 1) + "列");
}
break;
case 5:
if (cellStr.indexOf("出生日期") >= 0) {
} else {
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是出生日期");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
}
break;
case 6:
if (cellStr.indexOf("职务") >= 0
|| cellStr.indexOf("工种") >= 0) {
} else {
msgList
.add("表头不正确,请检查第1行第" + (i + 1)
+ "列必须是职务/工种");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
return 0;
}
break;
case 7:
if (cellStr.indexOf("身份证号") >= 0) {
} else {
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是身份证号");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
}
break;
case 8:
if (cellStr.indexOf("工作证号") >= 0) {
} else {
// "列");
msgList.add("表头不正确,请检查第1行第" + (i + 1) + "列必须是工作证号");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
}
break;
case 9:
if (cellStr.indexOf("工作证编号") >= 0) {
} else {
// msgList.add("表头不正确,请检查第1行第" + (i + 1) +
// "列");
msgList
.add("表头不正确,请检查第1行第" + (i + 1)
+ "列必须是工作证编号");
// if (fis != null) {
// try {
// fis.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return 0;
}
break;
default:
break;
}
}
}
boolean flagerror = false;
outer: for (int i = 1; i < rows; i++) {
Integer optionSize = 0;
HSSFRow row = sheet.getRow(i);
if (i == 7) {
System.out.println();
}
// System.out.println("----------" + (i + 1) +
// "行begin");
// // 如果中间有列为空; 也不计算在内;
if (row == null) {
// continue;
break;
}
System.out.println("---------");
for (int temp = 0; temp < cellCount; temp++) {
System.out.print((i + 1)
+ "测试行"
+ temp
+ "测试列 "
+ ReadExcelUtil.getStringByCell(row.getCell(temp))
.trim() + "\t");
;
}
System.out.println("---------");
// System.out.println("row======" + i + "sheet"
// + sheetindex);
if (row != null) {
Employee employee = null;
List<String> questionOptionlist = null;
for (int temp = 0; temp < cellCount; temp++) {
try {
if (true) {
System.out.print(ReadExcelUtil.getStringByCell(
row.getCell(temp)).trim()
+ "\t");
// String questionOption="";//
// 选项对单选多选有效,其他题型无效。
// 格式为:xx1|xx2|xx3|xx4
// System.out.print(i + "haang " + temp +
// "lie ");
switch (temp) {
case 0:
String str0 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str0 == null || str0.equals("")) {
// flagerror = true;
//
// msgList.add("工号不能为空,请检查第"
// + (i + 1) + "行第"
// + (temp + 1) + "列");
// break outer;
} else {
employee = new Employee();
// employeeNumber 工号
str0 = str0.replaceAll("\\.0", "");
employee.setEmployeeNumber(str0);
}
break;
case 1:
String str1 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str1 == null || str1.equals("")) {
flagerror = true;
msgList.add("车间不能为空,请检查第" + (i + 1)
+ "行第" + (temp + 1) + "列");
break outer;
} else if (hasSameOrgName(str1,
organiseList) == null) {
flagerror = true;
msgList.add("车间名称在数据库中不存在,请检查第"
+ (i + 1) + "行第" + (temp + 1)
+ "列");
break outer;
} else {
Organise tempOrg = hasSameOrgName(str1,
organiseList);
if (employee != null) {
employee.setOrganise(tempOrg);
}
}
break;
case 2:
// 班组
String str2 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str2 == null || str2.equals("")) {
// flagerror = true;
//
// msgList.add("班组不能为空,请检查第"
// + (i + 1) + "行第"
// + (temp + 1) + "列");
// break outer;
} else {
if (employee != null) {
employee.setBanZu(str2);
}
}
break;
case 3:
// 姓名
String str3 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str3 == null || str3.equals("")) {
flagerror = true;
msgList.add("姓名不能为空,请检查第" + (i + 1)
+ "行第" + (temp + 1) + "列");
break outer;
} else {
if (employee != null) {
employee.setName(str3);
}
}
break;
case 4:// sex
String str4 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
String questionType = ReadExcelUtil
.getStringByCell(row.getCell(5))
.trim();
if (str4 == null
|| str4.equals("")
|| (!str4.equals("男") && !str4
.equals("女"))) {
flagerror = true;
msgList.add("性别不能为空且只能为男或者女,请检查第"
+ (i + 1) + "行第" + (temp + 1)
+ "列");
break outer;
} else {
if (employee != null) {
if ("男".equals(str4)) {
employee.setSex(1);
} else if ("女".equals(str4)) {
employee.setSex(0);
}
}
}
break;
case 5:
String str5 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str5 == null || str5.equals("")) {
// flagerror = true;
//
// msgList.add("出生日期不能为空,请检查第"
// + (i + i) + "行第"
// + (temp + 1) + "列");
// break outer;
}
else {
try {
String data = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss")
.format(new SimpleDateFormat(
"yyyy-MM-dd")
.parse(str5));
employee.setBirthday(Timestamp
.valueOf(data));
// employee.setBirthday(new
// Timestamp(new
// SimpleDateFormat("yyyyMMdd").parse(str5).getTime()));
} catch (Exception e) {
// TODO Auto-generated catch
// block
try {
String data = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss")
.format(new SimpleDateFormat(
"yyyyMMdd")
.parse(str5));
employee.setBirthday(Timestamp
.valueOf(data));
} catch (Exception e1) {
// TODO Auto-generated
// cat
e1.printStackTrace();
flagerror = true;
msgList.add("出生日期格式有误,请检查第"
+ (i + i) + "行第"
+ (temp + 1) + "列");
// if (fis != null) {
// fis.close();
// }
break outer;
}
}
}
break;
case 6:
// worktype
String str6 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str6 == null || "".equals(str6)) {
flagerror = true;
msgList.add("职务不能为空,请检查第" + (i + 1)
+ "行第" + (temp + 1) + "列");
break outer;
} else if (!workTypeList.contains(str6
.trim())) {
workTypeList.add(str6.trim());
WType w = new WType();
w.setName(str6);
this.workTypeService.save(w);
employee.setWorkType(str6);
// flagerror = true;
// msgList.add("该工种/职务 未找到,请检查第"
// + (i + 1) + "行第"
// + (temp + 1)
// + "列,工种名称:" + str6);
// if (fis != null) {
// fis.close();
// }
// break outer;
} else {
employee.setWorkType(str6);
}
break;
case 7:
String str7 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str7 == null || "".equals(str7)) {
flagerror = true;
msgList.add("身份证号不能为空,请检查第" + (i + 1)
+ "行第" + (temp + 1) + "列");
// if (fis != null) {
// fis.close();
// }
break outer;
} else {
if (employee != null) {
str7 = str7.replaceAll("\\.0", "");
employee.setIdenty(str7);
if (emplist != null
&& emplist.size() > 0
&& emplist
.contains(employee)) {
// 原来含有;
for (int empindex = 0; empindex < emplist
.size(); empindex++) {
// 已经覆盖了hashcode
// 和equals ; 如果身份证号
// 相同 则 视为相同;
if (emplist.get(empindex)
.equals(employee)) {
// 原来含有id 的员工;
Employee oldEmployee = emplist
.get(empindex);
oldEmployee
.setWorkNumber(employee
.getWorkNumber());
oldEmployee
.setOrganise(employee
.getOrganise());
oldEmployee
.setBanZu(employee
.getBanZu());
oldEmployee
.setName(employee
.getName());
oldEmployee
.setSex(employee
.getSex());
oldEmployee
.setBirthday(employee
.getBirthday());
oldEmployee
.setWorkType(employee
.getWorkType());
oldEmployee
.setEmployeeNumber(employee
.getEmployeeNumber());
oldEmployee
.setGongZuoZhengBianHao(employee
.getGongZuoZhengBianHao());
employee = oldEmployee;
// System.out
// .println("被赋值的"
// + employee
// .getId());
emplist.set(empindex,
employee);
}
}
} else {
emplist.add(employee);
}
// if (emplist != null
// && emplist.size() > 0) {
//
// if (emplist.contains(employee)) {
// 覆盖 了equalse//
// 和hashcode;//
// 根据身份证号
// for (int empindex = 0; empindex <
// emplist
// .size(); empindex++) {
// if (emplist
// .get(empindex)
// .equals(
// employee)) {
//
// emplist.set(
// empindex,
// employee);// 设置下;
//
// employee
// .setId(emplist
// .get(
// empindex)
// .getId());// 把本员工的id
// // 设置为原来id;
//
// } else {
//
// emplist
// .add(employee);// 原来不包含;
//
// }
// }
// }
//
// }
}
}
break;
case 8:
// option 3
String str8 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str8 == null || "".equals(str8)) {
// flagerror = true;
// msgList.add("工作证号不能为空,请检查第"
// + (i + 1) + "行第"
// + (temp + 1) + "列");
// if (fis != null) {
// fis.close();
// }
// break outer;
} else {
if (employee != null) {
str8 = str8.replaceAll("\\.0", "");
employee.setWorkNumber(str8);
}
}
break;
case 9:
// option4
String str9 = ReadExcelUtil
.getStringByCell(row.getCell(temp))
.trim();
if (str9 == null || "".equals(str9)) {
flagerror = true;
msgList.add("工作证编号" + (i + 1) + "行第"
+ (temp + 1) + "列");
// if (fis != null) {
// fis.close();
// }
break outer;
} else {
if (employee != null) {
str9 = str9.replaceAll("\\.0", "");
employee
.setGongZuoZhengBianHao(str9);
employee.setState(1);
// 设置为普通用户
Role commonRole = (Role) this.roleService
.findById(1);
employee.setRole(commonRole);
}
if (employee.getId() == null
|| employee.getId() == 0) {
System.err
.println("save 被执行了-------");
this.employeeService.save(employee);
} else {
System.err
.println("update 被执行了-------");
this.employeeService
.update(employee);
}
successNumer++;
request.getSession().setAttribute(
"successNumer", successNumer);
}
break;
default:
break;
}
}
// try end;
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("----------");
}
}
// try {
// if (fis != null) {
// fis.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
}
// }
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
//
// emplist = new ArrayList<Employee>();
// workTypeList = new ArrayList<String>();// 清空 list;
//
//
// }
return successNumer;
}
private Organise hasSameOrgName(String name, List<Organise> orglist) {
if (orglist != null && orglist.size() > 0) {
for (Organise org : orglist) {
if (org.getName().equals(name)) {
return org;
}
}
}
return null;
}