使用DWR框架实现服务器反推技术

近日,为了实现用服务器端来控制客户端的显示,搜索了相关资料,看到使用Ajax的框架DWR可以实现此功能。现将有关代码贴出来,供大家参考。
示例1:由服务器每一秒钟给发一个信息过来客户端
1、 首先将dwr.jar文件放到工程的lib中。
2、 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<description>调试DWR,发布系统时应将其设为false</description>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<description>使用服务器推技术(反转AJAX)</description>
<param-name>activeReverseAjaxEnabled</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>
initApplicationScopeCreatorsAtStartup
</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>maxWaitAfterWrite</param-name>
<param-value>100</param-value>
</init-param>
<load-on-startup>4</load-on-startup>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ServerClientServlet</servlet-name>
<servlet-class>com.lhq.ServerClientServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>ServerClinetStartServlet</servlet-name>
<servlet-class>com.lhq.ServerClinetStartServlet</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServerClientServlet</servlet-name>
<url-pattern>/servlet/ServerClientServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ServerClinetStartServlet</servlet-name>
<url-pattern>/servlet/ServerClinetStartServlet</url-pattern>
</servlet-mapping>


<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3、 新建两个jsp页面
启动页server_client_test_start.jsp代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>server_client_test_start.jsp</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">
-->
</head>
<body>
<p><a href="servlet/ServerClinetStartServlet">点击此处开启服务器反推技术</a></p>
</body>
</html:html>
结果显示页server_client_test1.jsp代码如下:
<%@ page language="java" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />

<title>server_client _test.jsp</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">
-->
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type="text/javascript">
dwr.engine.setActiveReverseAjax(true);//起动dwr反推,在接收页面这句必须要有
function showMessage(msg)
{
//DWRUtil.setValue("showMsg",msg);
//换行转回车
var haha="<br />";
haha=haha.replace('<br />','\n');
var showMsg=document.getElementById("showMsg");
showMsg.value=showMsg.value+haha+msg;

}
</script>
</head>

<body>
<p>下面的信息来自于服务器端</p>

<textarea rows="20" cols="80" id="showMsg"></textarea>

<div id="showMsg"></div>
</body>
</html:html>
4、 创建包com.lhq
5、 创建ServerClientServlet.servlet,代码如下:
package com.lhq;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContext;
import org.directwebremoting.ServerContextFactory;


public class ServerClientServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public ServerClientServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//WebContext wctx1 = WebContextFactory.get();
ServerContext wctx = ServerContextFactory.get(getServletContext());
Collection<ScriptSession> sessions = wctx.getAllScriptSessions();

// Collection<ScriptSession> sessions =
// wctx.getScriptSessionsByPage("/poject/test.html");
request.setCharacterEncoding("ISO-8859-1");
response.setCharacterEncoding("ISO-8859-1");
String msg = new String(request.getParameter("msg").getBytes("ISO-8859-1"),"GBK");

if(msg==null)
{
msg = "服务器没有值出现";
}

ScriptBuffer script = new ScriptBuffer();
script.appendScript("showMessage(").appendData(msg)
.appendScript(");");

for (ScriptSession session : sessions) {
session.addScript(script);
}

}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}
6、创建ServerClinetStartServlet.servlet,代码如下:
package com.lhq;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServerClinetStartServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public ServerClinetStartServlet() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

ServerClientStart scsObj=new ServerClientStart();
scsObj.start();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request,response);
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}
6、 创建类ServerClientStart.class
package com.lhq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;

public class ServerClientStart extends Thread{

public ServerClientStart()
{
super();

}
public void run()
{
int i=1;
while(true)
{
try{
this.sleep(1000);

String str="第"+(i++)+"秒";
URL url=new URL("http://10.180.84.38/dwrTest/servlet/ServerClientServlet?msg="+str);//这里的http://10.180.84.38/dwrTest/改为本机和自己建的工程
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));

br.close();
}catch(Exception ex){
this.stop();
break;
}
}
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值