C#窗体和jsp通信
通过WebBrowser控件将jsp引入窗体程序
-
配置方法:
-
窗体程序
namespace B_Test
{
//配置1:写在namespace下,设置Com对外可访问
[System.Runtime.InteropServices.ComVisible(true)]
public partial class Form1 : Form
{}
}
public Form1()
{
InitializeComponent();
// 配置2:将当前类设置为可由脚本访问
webBrowser1.ObjectForScripting = this;
}
//配置3:通信所用的函数,被外部js调用的方法
public void MyMessageBox(string message)
{
//MessageBox.Show(message);
//jsp调用C#,C#调用自己的发送函数来返回数据
SendMessage();
}
private void SendMessage()
{
// 调用JavaScript的messageBox方法,并传入参数
object[] objects = new object[1];
String a1 = AI_V1.Text;
String a2 = AI_V2.Text;
String a3 = AI_V3.Text;
String a4 = AI_V4.Text;
String a5 = AI_V5.Text;
String a6 = AI_V6.Text;
String a7 = AI_V7.Text;
String a8 = AI_V8.Text;
String jicha = JiCha_V.Text;
String message = a1 + ";" + a2 + ";" + a3 + ";" + a4 + ";" + a5 + ";" + a6 + ";" + a7 + ";" + a8 + ";" + jicha;
objects[0] = message;
webBrowser1.Document.InvokeScript("GetMessage", objects);
}
- jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ConnectC#.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
#tb{
position:relative;
width:100%;
border:1px solid black;
border-collapse:collapse;
}
#tb th{
border:1px solid black;
width:50%;
}
#tb td{
border:1px solid black;
}
</style>
<script language="javascript" type="text/javascript">
/* 调用C#方法 */
function SendMessage(){
window.external.MyMessageBox('javascript访问C#代码');
}
<!-- 提供给C#程序调用的方法 -->
function GetMessage(message)
{
//alert(message);
var val = message.split(";");
var tb = document.getElementById("tb");
var rows = tb.rows;
for(var i=0;i<rows.length;i++){
var cells = rows[i].cells;
cells[1].innerText = val[i];
}
//guocheng.window.say();
//guocheng.window.document.GetMessage(message)//getElementById("button").value="调用结束";
}
</script>
</head>
<body>
<!-- This is my JSP page. <br>
<button onclick="window.external.MyMessageBox('javascript访问C#代码')">
javascript访问C#代码
</button> -->
<input type="button" value="获取数据" onclick="SendMessage();"/>
<br><br>
<div>
<table id="tb">
<tr><th>AI1</th><td></td></tr>
<tr><th>AI2</th><td></td></tr>
<tr><th>AI3</th><td></td></tr>
<tr><th>AI4</th><td></td></tr>
<tr><th>AI5</th><td></td></tr>
<tr><th>AI6</th><td></td></tr>
<tr><th>AI7</th><td></td></tr>
<tr><th>AI8</th><td></td></tr>
<tr><th>极差</th><td></td></tr>
</table>
</div>
</body>
</html>
- 效果如图,AI1-8的数据可以随意设置