DWR框架学习

我的理解:DWR框架是javaWeb中前后端直接交互的解决方案,用DWR框架,前端js能够直接调用后端服务,后端服务也可以直接调用前端js函数。

 

配置:

(1)需要Dwr.jar 包,pom配置如下:

<dependency>  
       <groupId>org.directwebremoting</groupId>  
       <artifactId>dwr</artifactId>  
       <version>3.0.M1</version>  
 </dependency>  

(2)在Web.xml中配置servelet,如下:

<!-- DWR配置 -->
    <servlet>
        <servlet-name>dwr-invoker</servlet-name>
        <servlet-class>
            org.directwebremoting.servlet.DwrServlet
        </servlet-class>
        <init-param>
            <param-name>
                org.directwebremoting.extend.ServerLoadMonitor
            </param-name>
            <param-value>
                org.directwebremoting.impl.PollingServerLoadMonitor
            </param-value>
        </init-param>
        <!-- 默认轮询的周期是5秒中,也就是5000毫秒.如果想改变这个默认值需要下面的配置改为6秒 -->
        <init-param>
            <param-name>disconnectedTime</param-name>
            <param-value>5000</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>crossDomainSessionSecurity</param-name>    
          <param-value>false</param-value>    
        </init-param>
    </servlet>

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

(3)实现一个后端服务,就是一个普通的类

public class MessageServiceImpl {
      public void sendMassage() {
        ScriptBuffer sb = new ScriptBuffer();
    sb.appendScript("alert(12345)");
        scriptSession.addScript(sb);       }   

}    

scriptSession对应每个链接的会话,通过写入script脚本去前端执行。scriptSession可以通过如下方式获取:

WebContext context = WebContextFactory.get();
ScriptSession session = context.getScriptSession();

 

(4)WEB-INF目录下创建dwr.xml文件

 


<dwr>    
<allow>
<create creator="new" javascript="MessageServiceImpl" scope = "session"> <param name="class" value=".....MessageServiceImpl"></param> </create>
</allow>
</dwr>

 

(5)jsp中调用后端服务

<%@page contentType="text/html" pageEncoding="UTF-8"%>  
<!DOCTYPE html>  
<html>  
    <head>  
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
        <title>JSP Page</title>  
        <script src="<%=request.getContextPath()%>/dwr/engine.js"></script>  
        <script src="<%=request.getContextPath()%>/dwr/interface/MessageServiceImpl.js"></script>  
          
        <script>  
            MessageServiceImpl.sendMessage();  
        </script>  
    </head>  
    <body>  
        <h1>Hello World!</h1>  
    </body>  
</html>

 

(6)接收后端推送

dwr.engine.setActiveReverseAjax(true);  

 

posted @ 2017-06-03 16:29  XD-Thinker  阅读(1595)  评论(1编辑  收藏  举报