基於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="測試提交" class="btn4" 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>


特別注意‘<html:form action="/myAction" target="myiframe">’中的target屬性的值一定要等於form結尾那個iframe的名稱(即name屬性),這是該實現方式的原理所在,就是說這個MyForm提交服務器後由服務器響應回來的數據填充到這個iframe裏面,而這個iframe是不可見的(display: none)。從而實現了提交後頁面沒有刷新的感覺。
接下來是服務器端的實現

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();
}
}
}

sendMsg這個java生成了一段js代碼將服務端的數據展示在了頁面,頁面會打出一個alert,如果你明白了這個原理那麼你可以改寫sendMsg和function msg(m),你可以將數據填到一個div中,這個效果就好像ajax一樣頁面連閃都不閃一下。
接下來實現長連接

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();
}
}
}


不停的做循環操作以求達到長連接,前臺會不停的打alert出來,這樣做實現了服務器端向客戶端推數據,同時服務器端的狀態可以實時反映到前臺,如果在你的項目中客戶點擊按鈕後服務器將執行大量的長時間的操作的時候而客戶又要實時監控操作的情況的時候不妨使用這種方式提升用戶體驗。隨便說一句IE支持這種玩法firefox等瀏覽器也支持
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章