问题描述
我想开发一个小功能,在前台jsp中列出几个应用服务器,然后选中某个应用服务器后,将服务器IP发送到后台Servlet,由servlet用sshxcute远程登录并执行aix中的脚本文件,并将执行结果返回到前台jsp。遇到的问题:前台使用jQuery(mathod用post)提交数据,后台用servlet接受数据,前台发送不同的数据后台servlet都能接受到不同的数据,但执行后的结果却是每次都一样。开发环境:oracleweblogicworkshop10.3使用技术:ajax(jQuery),jqueryeasyui,sshxcute代码servletpackagezbgl.servlet;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importzbgl.bean.AppServerBean;importzbgl.bean.CommonBean;publicclassAppServerServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;AppServerBeanbean=newAppServerBean();CommonBeancb=newCommonBean();protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{doGet(request,response);}protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");Stringoper=request.getParameter("oper");//cb.sysout(oper);if(oper==null){cb.out(response,"{"SUCCESS":false,"MSG":"requestmethodisnull!"}");}elseif(oper.equalsIgnoreCase("getAppServerGrid"))bean.getAppServerGrid(request,response);//elseif(oper.equalsIgnoreCase("excuteScript")){newAppServerBean().executeScript(request,response);//}elseif(oper.equalsIgnoreCase("netMonitor"))newAppServerBean().netMonitor(request,response);//else{cb.out(response,"{"SUCCESS":false,"MSG":"+this.getServletName()+":nomethodforrequestmethod:"+oper+"!"}");}}}
javaBeanpackagezbgl.bean;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.PreparedStatement;importjava.util.Arrays;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importnet.neoremind.sshxcute.core.ConnBean;importnet.neoremind.sshxcute.core.Result;importnet.neoremind.sshxcute.core.SSHExec;importnet.neoremind.sshxcute.exception.TaskExecFailException;importnet.neoremind.sshxcute.task.CustomTask;importnet.neoremind.sshxcute.task.impl.ExecCommand;importnet.sf.json.*;importzbgl.bean.Json;importzbgl.bean.ExeShellBean;importnet.sf.json.JSONObject;publicclassAppServerBean{publicvoidexecuteScript(HttpServletRequestrequest,HttpServletResponseresponse){Jsonjson=newJson();DBAccessdb=newDBAccess();PreparedStatementps=null;CommonBeancb=newCommonBean();ResultSetrs=null;Stringp_id=request.getParameter("p_id");StringscriptType=request.getParameter("script_type");StringgetField="script_"+scriptType;SSHExecssh=null;Stringip="";Stringuser="";Stringpass="";StringscriptName="";StringjsonMsg=null;try{db.openConnectionPool();Stringsql="selectapp_ip,script_user,script_pass,"+getField+"fromDIC_PROJECTwherep_id=?";ps=db.getConn().prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);ps.setString(1,p_id);rs=ps.executeQuery();if(!rs.next()){json.setMsg("没有取到脚本运行用户名、密码或IP地址...");json.setSuccess(false);}else{ip=rs.getString(1);user=rs.getString(2);pass=rs.getString(3);scriptName=rs.getString(4);jsonMsg="取到的";if(ip==null){jsonMsg+="地址";}if(user==null||pass==null){jsonMsg+=(jsonMsg.equals("取到的")?"用户信息":"、用户信息");}if(scriptName==null){jsonMsg+=(jsonMsg.equals("取到的")?"脚本名":"、脚本名");}jsonMsg+="有误";if(!jsonMsg.equals("取到的有误")){json.setSuccess(false);json.setMsg(jsonMsg);}else{//调用执行远程脚本的类ExeShellBeanexeShellBean=newExeShellBean();json=exeShellBean.executeScript(ip,user,pass,scriptName);exeShellBean=null;}}}catch(SQLExceptione){json.setMsg("数据库操作错误!");json.setSuccess(false);System.out.println(e.getMessage());e.printStackTrace();}catch(Exceptione){json.setMsg("命令运行失败!原因:"+e.getMessage());json.setSuccess(false);System.out.println("error2:"+e.getMessage());e.printStackTrace();}finally{if(cb!=null)cb=null;if(ssh!=null)ssh.disconnect();db.closeConn();newCommonBean().out(response,json.writeJson());}}}
sshxcute执行远程脚本packagezbgl.bean;importjava.util.HashMap;importjava.util.Arrays;importjava.util.Iterator;importjava.util.Map;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importnet.neoremind.sshxcute.core.*;importnet.neoremind.sshxcute.exception.*;importnet.neoremind.sshxcute.task.*;importnet.neoremind.sshxcute.task.impl.*;importnet.sf.json.JSONArray;importnet.sf.json.JSONObject;importzbgl.bean.Json;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.PreparedStatement;publicclassExeShellBean{publicJsonexecuteScript(Stringip,Stringuser,Stringpass,StringscriptName){Jsonjson=newJson();SSHExecssh=null;try{//传入的IP在这里看时每次都和前台传过来的一致ConnBeanconnBean=newConnBean(ip,user,pass);ssh=SSHExec.getInstance(connBean);//Stringcommand="./"+scriptName;//ssh.connect();if(!ssh.connect()){json.setMsg("连接服务器错误...");json.setSuccess(false);}else{//CustomTaskct1=newExecCommand(command);CustomTaskct1=newExecShellScript("./"+scriptName);Resultres=ssh.exec(ct1);if(res.isSuccess){json.setMsg(res.sysout.replace("n","<br><br>"));}else{if(res.error_msg.length()==0)json.setMsg(res.sysout.replace("n","<br><br>"));else{json.setMsg("脚本运行失败!错误信息:<br>"+res.error_msg.replace("n","<br>"));json.setSuccess(false);}}}connBean=null;if(ssh!=null)ssh.disconnect();returnjson;}catch(TaskExecFailExceptione){json.setMsg("命令运行失败!"+e.getMessage());json.setSuccess(false);returnjson;//System.out.println("error1:"+e.getMessage());//e.printStackTrace();}catch(Exceptione){json.setMsg("命令运行失败!原因:"+e.getMessage());json.setSuccess(false);returnjson;//System.out.println("error2:"+e.getMessage());//e.printStackTrace();}}}
jsp<%@pagelanguage="java"contentType="text/html;charset=UTF-8"pageEncoding="UTF-8"%><%StringbasePath=(String)session.getAttribute("basePath");//%><html><body><scriptsrc="<%=basePath%>js/zbgl/rcgl/rcglPara.js"type="text/javascript"charset="utf-8"></script><scriptsrc="<%=basePath%>js/zbgl/rcgl/rcglAppServerMaintence.js"type="text/javascript"charset="utf-8"></script><divid="rcgl_layout"class="easyui-layout"data-options="fit:true,border:0"><divregion="north"id="north"style="height:300px;padding:0px;border:0px;"><tableid="rcglAppServerMaintence"border="0"style="overflow:scroll;"></table><divid="appServMantainceToolbar"style="height:30px;text-align:left;padding:5px;"><table><tr><!--<td><labelfor="searchValueApp">条件</label><inputtype="text"id="searchValueApp"title="输入查询条件并按回车键即在姓名、电话中查找符合条件的记录"name="searchValueXxc"/><aid="btnAppFind"href="#"title="在姓名、电话中查找符合条件的记录"class="easyui-linkbutton"data-options="iconCls:'icon-search'">查找</a></td><td></td>--><td><aid="zhcx_btnSeeApp"href="#"class="easyui-linkbutton"data-options="iconCls:'icon-search'">查看</a></td><td><aid="zhcx_btnStartApp"href="#"class="easyui-linkbutton"data-options="iconCls:'icon-ok'">启动</a></td><td><aid="zhcx_btnStopApp"href="#"class="easyui-linkbutton"data-options="iconCls:'icon-cancel'">停止</a></td><td><aid="zhcx_btnRestartApp"href="#"class="easyui-linkbutton"data-options="iconCls:'icon-reload'">重启</a></td><td><aid="zhcx_netMonitor"href="#"class="easyui-linkbutton"data-options="iconCls:'icon-forward'">网络状态</a></td><td></td></tr></table></div></div><divregion='center'style="padding:0px;border-width:1px0px0px0px;overflow:hidden;"><tableid="netStatus"style="border:0px;border-width:0px0px0px0px;overflow:scroll"></table><divid="scriptResult"class="easyui-panel"data-options="closed:true,title:'脚本运行结果'"style="border:0px;border-width:0px0px0px0px;overflow:auto;margin:5px;"></div></div></div><divid="zhcx_app_dialog"class="easyui-dialog"data-options="closed:true,closeable:false,modal:true,title:''"style="color:red;font-size:22px;margin:10px;width:500px;height:70px;"">正在等待服务器返回数据,请稍等...</div></body></html>
解决方案
本帖最后由 jiangsongnian 于 2014-09-17 09:20:26 编辑
解决方案二:
jsfunctionloadRcglAppServerMaintence(plugin,title){varservletUrl=basePath+'AppServerServlet.do?oper=';var$dg=null;vardialog;varp_id=-1,script_type;$dg=$('#'+plugin);varidField='p_id';varsortName='p_id';varrows;$dg.datagrid({toolbar:'#appServMantainceToolbar',//title:title,//width:'auto',//height:maxH1,//fitColumns:true,iconCls:'icon-save',autoRowHeight:false,singleSelect:true,striped:true,fit:true,method:'get',url:servletUrl+'getAppServerGrid',sortName:sortName,sortOrder:'asc',remoteSort:true,idField:idField,rownumbers:true,onSelect:function(rowIndex,rowData){p_id=rowData['P_ID'];},columns:[[{field:'P_ID',title:'ID',width:120,align:'center',hidden:true},{field:'P_NAME',title:'应用名称',width:140,align:'center'},{field:'P_MANAGER1',title:'第一负责人',width:80,align:'center'},{field:'P_MANAGER2',title:'第二负责人',width:80,align:'center',hidden:true},{field:'APP_IP',title:'服务器地址',width:90,align:'center',sortable:true},{field:'APP_PORT',title:'端口',width:70,align:'center'}//{field:'AVIENDTIME',title:'过期时间',width:120,align:'center'},//{field:'QUERY_CF',title:'QUERY_CF',width:100,align:'center'},//{field:'QUERY_TOPIC',title:'QUERY_TOPIC',width:100,align:'center'}]]});$('#btnAppFind').on('click',function(){search('searchValueApp',$dg,'P_NAME,P_MANAGER1,P_MANAGER2,APP_IP');$('#searchValueApp').focus();});bindButtonToInputBox('searchValueApp','btnAppFind');$('#searchAppValue').focus();$('#zhcx_btnSeeApp').on('click',function(){execScript(p_id,'see');});$('#zhcx_btnStopApp').on('click',function(){execScript(p_id,'stop');});$('#zhcx_btnStartApp').on('click',function(){execScript(p_id,'start');});$('#zhcx_btnRestartApp').on('click',function(){execScript(p_id,'restart');});//发送IP、远程脚步类型参数到servletvarexecScript=function(pId,scriptType){if(pId==-1){returnfalse;}console.info(pId+''+scriptType);$('#zhcx_app_dialog').dialog('open');$('#scriptResult').panel('open');$('#scriptResult').panel({content:''});$('#netStatus').datagrid('getPanel').panel('close');//$.post(servletUrl+'excuteScript',{p_id:pId,script_type:scriptType},//ajax发送、接收数据$.ajax({type:'post',url:servletUrl+'excuteScript',data:'p_id='+pId+'&script_type='+scriptType,dataType:'json',success:function(data){closeDialog();$('#scriptResult').panel({content:data.msg});}});}netMonitor(p_id);//$('#divAddLjxdQueryUser').dialog('open');$('#zhcx_netMonitor').on('click',function(){$('#scriptResult').panel({content:''})$('#scriptResult').panel('close');$('#netStatus').datagrid('getPanel').panel('open');getNetStatus(p_id);});functiongetNetStatus(pId){if(pId==-1){returnfalse;}$('#zhcx_app_dialog').dialog('open');$.ajax({type:'post',url:servletUrl+"netMonitor",data:"p_id="+pId,dataType:'json',success:function(data){closeDialog();if(data.success){$("#netStatus").datagrid('loadData',data);}else{alert(data.msg);}}});}functionnetMonitor(pId){$("#netStatus").datagrid({title:'网络状态',rownumbers:true,width:'auto',//height:maxH2,//autoRowHeight:false,singleSelect:true,striped:true,fit:true,method:'get',remoteSort:false,//url:servletUrl+'netMonitor&p_id='+pId,sortName:'CONNECTCOUNT',sortOrder:'desc',//remoteSort:true,//idField:'IP',columns:[[{field:'IP',title:'IP地址',width:120,align:'center',sortable:true},{field:'CONNECTCOUNT',title:'连接数',width:140,align:'center',sortable:true},{field:'CONNECTTYPE',title:'连接类型',width:140,align:'center',sortable:true},{field:'ISNORMAL',title:'状态',width:80,align:'center',sortable:true}]],rowStyler:function(index,row){if(row.ISNORMAL=='异常'){return'color:#f00;';}}});}var$dialog;functioninitDialog(){$dialog=$('#zhcx_app_dialog').dialog({title:'',width:500,height:50,closed:true,closeable:false,modal:true});}functionshowDialog(){$('#zhcx_app_dialog').dialog('open');}functioncloseDialog(){$('#zhcx_app_dialog').dialog('close');}}