论坛首页 Web前端技术论坛

为何这样:前台jsp发送不同参数,servlet返回同样的结果

浏览 1586 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2014-09-17   最后修改:2014-09-17
我想开发一个小功能,在前台jsp中列出几个应用服务器,然后选中某个应用服务器后,将服务器IP发送到后台Servlet,由servlet用sshxcute远程登录并执行 aix 中的脚本文件,并将执行结果返回到前台jsp。
遇到的问题:前台使用jQuery (mathod用post)提交数据,后台用servlet接受数据,前台发送不同的数据后台servlet都能接受到不同的数据,但执行后的结果却是每次都一样。如何解决?
开发环境:oracle weblogic workshop 10.3
使用技术:ajax(jQuery),jquery easyui,sshxcute
代码

servlet
package zbgl.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import zbgl.bean.AppServerBean;
import zbgl.bean.CommonBean;

public class AppServerServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	AppServerBean bean = new AppServerBean();
	CommonBean cb = new CommonBean();
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

			doGet(request, response);
	
	}
	
	protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String oper = request.getParameter("oper");
		//cb.sysout(oper);
		if(oper==null) {
			cb.out(response, "{\"SUCCESS\":false, \"MSG\": \"request method is null!\"}");
		} 
		else if(oper.equalsIgnoreCase("getAppServerGrid"))  
			bean.getAppServerGrid(request, response);//
		else if(oper.equalsIgnoreCase("excuteScript")) { 
			new AppServerBean().executeScript(request, response);//
		}
		else if(oper.equalsIgnoreCase("netMonitor"))  
			new AppServerBean().netMonitor(request, response);//
		else{
			cb.out(response, "{\"SUCCESS\":false, \"MSG\": "+ this.getServletName() + ": no method for request method:"+oper+" !\"}");
		}
	}
	
}





javaBean
package zbgl.bean;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.neoremind.sshxcute.core.ConnBean;
import net.neoremind.sshxcute.core.Result;
import net.neoremind.sshxcute.core.SSHExec;
import net.neoremind.sshxcute.exception.TaskExecFailException;
import net.neoremind.sshxcute.task.CustomTask;
import net.neoremind.sshxcute.task.impl.ExecCommand;
import net.sf.json.*;
import zbgl.bean.Json;
import zbgl.bean.ExeShellBean;
import net.sf.json.JSONObject;

public class AppServerBean {

	public void executeScript(HttpServletRequest request, HttpServletResponse response) {
		Json json = new Json();
		DBAccess db = new DBAccess();
		PreparedStatement ps = null;
		CommonBean cb = new CommonBean();
		ResultSet rs = null;
		String p_id = request.getParameter("p_id");
		String scriptType = request.getParameter("script_type");
		String getField = "script_" + scriptType;

		SSHExec ssh = null;
		String ip = "";
		String user = "";
		String pass = "";
		String scriptName = "";
		String jsonMsg = null;
		try {
			db.openConnectionPool();
			String sql = "select app_ip,script_user,script_pass," + getField + " from DIC_PROJECT where p_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 {
[color=#FF0000]

//调用执行远程脚本的类
					ExeShellBean exeShellBean = new ExeShellBean();
					json = exeShellBean.executeScript(ip, user, pass,scriptName);
					exeShellBean = null;
[/color]				}
			}
		} catch (SQLException e) {
			json.setMsg("数据库操作错误!");
			json.setSuccess(false);
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			json.setMsg("命令运行失败!原因:" + e.getMessage());
			json.setSuccess(false);
			System.out.println(" error 2 : " + e.getMessage());
			e.printStackTrace();
		} finally {
			if(cb != null)
				cb = null;
			if(ssh != null)
				ssh.disconnect();
			db.closeConn();
			new CommonBean().out(response, json.writeJson());
		}
	}
}


sshxcute执行远程脚本
package zbgl.bean;

import java.util.HashMap;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.neoremind.sshxcute.core.*;
import net.neoremind.sshxcute.exception.*;
import net.neoremind.sshxcute.task.*;
import net.neoremind.sshxcute.task.impl.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import zbgl.bean.Json;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;

public class ExeShellBean {

	public Json executeScript(String ip, String user, String pass,String scriptName) {
		Json json = new Json();
		SSHExec ssh = null;
		try {
//传入的IP在这里看时每次都和前台传过来的一致
                          [color=#FF0000]ConnBean connBean = new ConnBean(ip, user, pass);[/color]
			ssh = SSHExec.getInstance(connBean);
			//String command =  "./" + scriptName;
			//ssh.connect();
			if(!ssh.connect()){
				json.setMsg("连接服务器错误...");
				json.setSuccess(false);	
			}else{
				//CustomTask ct1 = new ExecCommand(command);
				CustomTask ct1 = new ExecShellScript("./" + scriptName);
				Result res = 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();
			return json;
		} catch (TaskExecFailException e) {
			json.setMsg("命令运行失败!" + e.getMessage());
			json.setSuccess(false);
			return json;
			//System.out.println(" error 1 : " + e.getMessage());
			//e.printStackTrace();
		} catch (Exception e) {
			json.setMsg("命令运行失败!原因:" + e.getMessage());
			json.setSuccess(false);
			return json;
			//System.out.println(" error 2 : " + e.getMessage());
			//e.printStackTrace();
		}
	}
}



jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
	String basePath = (String)session.getAttribute("basePath");// 
%>
<html>
<body>
	<script src="<%=basePath%>js/zbgl/rcgl/rcglPara.js" type="text/javascript" charset="utf-8"> </script>
	<script src="<%=basePath%>js/zbgl/rcgl/rcglAppServerMaintence.js" type="text/javascript" charset="utf-8"> </script>
	<div id="rcgl_layout" class="easyui-layout" data-options="fit:true,border:0">
		<div region="north" id="north" style="height:300px; padding: 0px; border: 0px;"> 
			<table id="rcglAppServerMaintence" border="0" style=" overflow: scroll;"></table>
			<div id="appServMantainceToolbar" style=" height:30px; text-align: left; padding: 5px;">
				<table>
					<tr>
						<!-- 
						<td><label for="searchValueApp">条件</label><input type="text" id="searchValueApp" title="输入查询条件并按回车键即在姓名、电话中查找符合条件的记录" name="searchValueXxc"/>
						<a id="btnAppFind" href="#" title="在姓名、电话中查找符合条件的记录" class="easyui-linkbutton" data-options="iconCls:'icon-search'">查找</a> </td>
						<td></td>
						 -->
		 				<td><a id="zhcx_btnSeeApp" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-search'">查看</a></td>
						<td><a id="zhcx_btnStartApp" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-ok'">启动</a></td>
						<td><a id="zhcx_btnStopApp" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'">停止</a></td>
						<td><a id="zhcx_btnRestartApp" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-reload'">重启</a></td>
						<td><a id="zhcx_netMonitor" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-forward'">网络状态</a></td>
						<td></td>
					</tr>
				</table>
			</div>
		</div>
		<div region='center' style="padding: 0px;border-width: 1px 0px 0px 0px; overflow: hidden;">
			<table id="netStatus" style="border: 0px;border-width: 0px 0px 0px 0px; overflow: scroll"></table>
			<div id="scriptResult" class="easyui-panel" data-options="closed:true,title:'脚本运行结果'"style="border: 0px;border-width: 0px 0px 0px 0px; overflow: auto;margin:5px;"></div>
		</div>
	</div>
	<div id="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>



js
    function loadRcglAppServerMaintence(plugin,title){   
        var servletUrl = basePath + 'AppServerServlet.do?oper=';
        var $dg = null;
        var dialog;
        var p_id = -1,script_type;
         
        $dg = $('#'+plugin);
        var idField = 'p_id';
        var sortName = 'p_id';
        var rows;
        $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、远程脚步类型参数到servlet
        var execScript = function(pId, scriptType) {
            if(pId==-1){
                 
                return false;
            }
            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);
        });
         
         
        function getNetStatus (pId){
            if(pId==-1){
                 
                return false;
            }
            $('#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);
                     }
                   }
            });
        }
         
        function netMonitor ( 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 ;
        function initDialog () {
            $dialog=$('#zhcx_app_dialog').dialog({  
                title: '',  
                width: 500,  
                height: 50,  
                closed: true, 
                closeable: false,
                modal: true  
            }); 
        }
         
        function showDialog (){
            $('#zhcx_app_dialog').dialog('open');
        }
        function closeDialog (){
            $('#zhcx_app_dialog').dialog('close');
        }
 
     
    }
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics