HttpClient工具类和servlet实现跨项目传输数据

文章描述了两个系统A和B之间的数据交互过程,A系统前端通过Ajax将用户输入的数据发送到B系统,B系统中的Servlet处理请求并操作数据库,最后通过HTTP响应将结果返回给A系统。涉及到了Ajax、HttpClien.doPost、表单提交以及前后端交互的技术细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前提

两个系统A和B,在A系统的前端界面上,输入数据,写到B系统连接的数据库中。

实现逻辑

系统A和B都要启动,A系统前端界面应该是个表单,点提交调用js函数,在函数中用Ajax将数据从前端界面传到后端方法,方法中去用HttpClien.doPost实现跨系统转发,进入B系统中,在这之前B系统中定义好了一个接口servlet方法,也就是B_servlet去继承HttpServlet,在里面B_servlet.dopost方法中实现逻辑并且将数据写到数据库中,执行完成后HttpClien.doPost返回值,然后带着这个值到A系统前端Ajax的回调函数中的参数,然后判断是否成功。

具体实现

A系统 前端界面,form表单:

<form name="form"
 class="l-edit-form">
    <table id="editTable" class="editTable" width="500px">
        <tr id="header">
            <td colspan="3" class="header">添加</td>
        </tr>
            <tr>
            <td align="left" width="60px">编号:</td>
            <td align="left" width="180px" colspan="2">
                        //注意这个name属性,它要和id属性会在create()方法中用来得到输入的数据             
            <s:textfield name="whiteListProfile.dvcid" id="dvcid" ltype="text" maxlength="20" /> 
                </td>
        </tr>
        
        <tr>
                          //调用create()方法                          
            <td colspan="3" align="right"><input type="button"
                onclick="create();" 
                class="l-button l-button-submit" value="添加" /> <input
                type="button" onclick="javascript:history.back(-1);" 
                class="l-button l-button-submit" value="返回" /></td>
        </tr>
    </table>
</form>

A系统 create()方法,里面包含Ajax将前端输入的数据传到后端

function create() {
    var dvcid = $("#dvcid").val();        
    //传过去的数据一般都是json格式
         var respData = [
             {name:'whiteListProfile.dvcid',value:dvcid}
             ];
        
        
    $.ajax( {
        type : 'post',
                  //Ajax用post方法将输入传到后端,地址是url,这个url是在struts.xml中配置好的
                  //去看struts.xml中,代码会运行跳到addDevice()方法,去看addDevice()方法                  
        url : '<%=basePath%>DvcWhiteListManage_addDevice.action',
        data : respData,
        async : false,
        dataType : 'json',
              //Ajax的回调函数,执行完逻辑之后再来执行这个函数
              //success是这个跳转是否状态正常,如何跳转正常运行success中的方法,不正常就运行error中的方法
              //其中的参数data是跳转过后返回的结果                  
        success : function(data) {
        if(data.respCode == 1) {
              alert("设备添加成功");
                         //要是成功的话,跳转到另外一个页面
              window.location.href = "<%=basePath%>DvcWhiteListManage_search.action";
          }
        if(data.respCode == 0) {
                  alert(data.respData);
              }
        },
        error : function(data) {
                
              alert("该设备已存在,该设备的编号为:"+dvcid);
              window.location.href = "<%=basePath%>DvcWhiteListManage_search.action";
        }
    });
}

A系统 addDevice()方法

public String addDevice() { 
    //测试一下有没有将数据传过来,whiteListProfile是一个对象
    String dvcid = whiteListProfile.getDvcid();
    System.out.println(dvcid);
    
        //调用HttpClientUtil工具类中的dopost方法,这个url是B系统的地址,将dvcid传过去
        //在这里这个url是http://localhost:8080/RKICA/KDH_Import,不接着进行下面的代码,
        //而是进入到这个地址中去也就是到B系统,先去看B系统的web.xml,里面会配置这个地址对应的类,在这里是
        //<servlet>
    //    <servlet-name>KDH_Import</servlet-name>
    //    <servlet-class>com.urovo.kms.api.servlet.KDHImportServlet</servlet-class>
    //    <load-on-startup>1</load-on-startup>
    //</servlet>
        //<servlet-mapping>
    //    <servlet-name>KDH_Import</servlet-name>
    //    <url-pattern>/KDH_Import</url-pattern>    
    //</servlet-mapping>
        //根据上面的配置就会知道/KDH_Import,是跳转到KDHImportServlet类中的,然后会去执行
        //KDHImportServlet类中的dopost方法或者doget方法,先去看KDHImportServlet类的dopost方法
        //看完再调回来接着运行下面的代码
        
        
        //执行完后返回的结果就是jsonStr,
        //jsonStr是由JSON格式转化成了字符串,因为在流中数据要以字符串的形式传递         
    String jsonStr = HttpClientUtil.doPost(url, dvcid);
        //将string再转化成JSON格式
    JSONObject json = JSONObject.parseObject(jsonStr);
        //测试数据能不能输出
    System.out.println(json);
    Integer code = json.getInteger("code");
    String data = json.getString("data");
        //前端设置的respJsonData,这也是一个JSON格式的对象
    respJsonData.setRespCode(code);
    respJsonData.setRespData(data);
        //去看strut2.xml,这里是A系统的前端界面,接着到create()方法中,执行Ajax的回调函数
        //回去看A系统的create()方法中的Ajax
    return "createWhiteList";

    
 }

A系统 网上找一个HttpClient工具类的代码,用它里面的dopost方法,这个不用管,大部分都一样,作用就是将数据content传到url对应的地址中

public static String doPost(String url, String content, String contentType)
            throws HttpClientException {
    String result = null;

    HttpEntity resEntity = null;
    CloseableHttpResponse response = null;
    try {
        HttpPost post = new HttpPost(url);
        if (contentType != null) {
        post.setHeader("Content-Type", contentType);
    }
    post.setEntity(new StringEntity(content, DEFAULT_CHARSET));
            
            
    response = client.execute(post);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new HttpClientException("请求失败! STATUS CODE:"
                + response.getStatusLine().getStatusCode());
    }

    resEntity = response.getEntity();
    result = null == resEntity ? "" : EntityUtils.toString(resEntity,
                    DEFAULT_CHARSET);
    } catch (UnsupportedEncodingException e) {
        throw new HttpClientException(e);
    } catch (ClientProtocolException e) {
        throw new HttpClientException(e);
    } catch (IOException e) {
        throw new HttpClientException(e);
    } finally {
        try {
            if (resEntity != null) {
                EntityUtils.consume(resEntity);
            }
            if (response != null) {
                response.close();
            }

    } catch (IOException e) {
        throw new HttpClientException(e);
    }

    }
    return result;
}

B系统,Servlet类中的dopost方法

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        
    //测试是否跳转到dopost方法,看控制台是否打印hello
    //System.out.println("hello"); 
        
    
        // 获取请求数据

    String dvcid =null; 
    BufferedReader reader =req.getReader();

        
    dvcid = reader.readLine(); 
        //测试dvcid有没有传过来
    System.out.println(dvcid);
 

    //添加白名单的逻辑
        //用JSON的格式去放数据
    JSONObject json = new JSONObject();
        // SpringContextUtil也是一个工具类,网上找找,它的getBean方法中的参数去
        //spring-mybatis-bean.xml中去查,一定要配置类似于下面,因为我们要用到dvcWhitelistService
        //中的方法
        //<bean id="dvcWhitelistService" class="com.urovo.kms.dvcwhitelist.service.impl.DvcWhitelistServiceImpl">
    //    <property name="dvcWhitelistDao">
    //        <ref bean="dvcWhitelistDao" />
    //    </property>
        //</bean>
       //<bean id="dvcWhitelistDao" class="com.urovo.kms.dvcwhitelist.dao.impl.DvcWhitelistDaoImpl">
    dvcWhitelistService = (DvcWhitelistService) SpringContextUtil.getBean("dvcWhitelistService");
    
        //这是方法为了去查看数据库中是否已经有了dvcid,要是有了就不能添加
        int res = dvcWhitelistService.queryDvcInWhiteList(dvcid); 
        
    if(res >0){

        json.put("code", 0);
        json.put("data", "该设备在白名单中已存在");
    }
        //数据库中没有dvcid,可以添加,这个方法就是添加到数据库中,count是返回状态,添加成功或者失败          
    int count = dvcWhitelistService.createWhiteList(dvcid);
              
    if (count > 0) { 

        json.put("code", 1);
        json.put("data", "设备添加白名单成功");
    }else{ 

        json.put("code", 0);
        json.put("data", "设备添加白名单失败");
    }
        //执行完成了再传回A系统中去,这是个流,要json.toString()变成字符串去传输
        //这个时候json就是上面addDevice()中的jsonStr,接着执行addDevice()的代码        
    PrintWriter out = resp.getWriter();
    out.println(json.toString());

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值