基于iframe的HTTP长连接实现
关于什么是http长连接我不废吐沫了,有专业的解释(http://www.ibm.com/developerworks/cn/web/wa-lo-comet/)你可以去看看
我们介绍一下在struts下的实现
首先写一个test.jsp(写一些片段)
<html:form action="/myAction" target="myiframe"> <%-- 这里写你的页面代码 --%> <center><input type="button" value="测试提交" onClick="javascript:test();"></center> </html:form> <iframe name="myiframe" id="myiframe" style="display: none" mce_style="display: none"></iframe> <mce:script language="JavaScript"><!-- function orderGen(){ document.MyForm.action.value = 'test'; document.MyForm.submit(); } function msg(m){ alert(m); } // --></mce:script> public class MyAction extends DispatchAction{ public ActionForward test(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { String result = "hello I'm server";//要打印到前台的字符 sendMsg(result,response,"msg");//msg是test.jsp中的那个js方法的名称 return null;//必须返回null } //以下方法的意思是将msg打到前台页面调用前台的“function msg(m)”方法进行显示 protected void sendMsg(String msg, HttpServletResponse response, String javascriptMethod) { try { response.setContentType("text/html;charset=GBK"); response.getWriter().write( "<mce:script type="text/javascript"><!-- parent." + javascriptMethod + "("" + msg + ""); // --></mce:script>"); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } } } public class MyAction extends DispatchAction{ public ActionForward test(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { int i = 0; boolean boo = true; String result = null; while(boo){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } result = "hello I'm server"+i;//要打印到前台的字符 sendMsg(result,response,"msg");//msg是test.jsp中的那个js方法的名称 i++; if(i==100){ boo = false; } } return null; } //以下方法的意思是将msg打到前台页面调用前台的“function msg(m)”方法进行显示 protected void sendMsg(String msg, HttpServletResponse response, String javascriptMethod) { try { response.setContentType("text/html;charset=GBK"); response.getWriter().write( "<mce:script type="text/javascript"><!-- parent." + javascriptMethod + "("" + msg + ""); // --></mce:script>"); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } } }