最近.NET项目上使用JAVA项目中的jsp页面,使用到跨域的信息交互。
jsp端代码,通过监听来自.NET项目所在IP地址,来请求.NET一般处理程序,实现jsp交互信息保存到.NET中:
window.addEventListener('message', function(event){ // 通过origin属性判断消息来源地址 if (event.origin == 'http://192.168.11.195') { if(event.data=='1'){ var xmlStr = getXmlStr(); var sysId1= '1111222'; var userId1 = '22211112'; var menus1 = xmlStr; var callback1='?'; var url = 'http://192.168.11.195/BPMS/WebService/MessageExchange.ashx'; $.ajax({ url:url, data: {sysId:sysId1,userId:userId1,menus:menus1,callback:callback1}, dataType:'jsonp', type:'post', processData: true, success:function(data){ alert(data); }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); } }); } } }, false);
.NET页面代码,主要是通过向jsp端页面发送带标记请求信息:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Role_InfoOuter.aspx.cs" Inherits="AT.Web.ATBase.SysUser.Role_InfoOuter" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="../../Themes/Scripts/jquery-1.8.2.min.js"></script> <script type="text/javascript"> $(function () { $("#btn").click(function () { test(); }); function test() { var ifr = document.getElementById('iframe'); var targetOrigin = 'http://192.168.11.10:8080'; ifr.contentWindow.postMessage('1', targetOrigin); }; }); </script> </head> <body> <form id="form1" runat="server"> <div> <iframe id="iframe" src="http://192.168.11.10:8080/ATMxgraphBS/grapheditor/Atgraphright.jsp"></iframe> <input type="button" value="保存" id="btn" /> </div> </form> </body> </html>
using AT.DataBase.SqlServer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace AT.Web.WebService { /// <summary> /// MessageExchange 的摘要说明 /// </summary> public class MessageExchange : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string callback = (context.Request["callback"] ?? "").ToString(); string sysId = (context.Request["sysId"] ?? "").ToString(); string userId = (context.Request["userId"] ?? "").ToString(); string menu = (context.Request["menus"] ?? "").ToString(); string msg = SaveMessage(sysId, userId, menu); context.Response.Write(msg); context.Response.End(); } /// <summary> /// 保存业务逻辑 /// </summary> /// <param name="sysId"></param> /// <param name="userId"></param> public string SaveMessage(string sysId, string userId, string menu) { SqlServerHelper db = new SqlServerHelper("Server=192.168.11.201;Database=AT_UnifiedAuthorityDB;Uid=sa;Pwd=apesm;"); StringBuilder sb = new StringBuilder(); sb.Append("insert into Test(T1,T2,T3) values('" + sysId + "','" + userId + "','" + menu + "')"); int cnt = db.ExecuteBySql(sb); if (cnt > 0) { return "OK"; } else { return "NO"; } } public bool IsReusable { get { return false; } } } }