dwr+springboot實現java消息推送瀏覽器【無dwr配置文件】

因爲本人在實際項目開發中有涉及到流程跑批,每一個節點順序點擊執行後必須刷新頁面才能看到狀態是否變動。從客戶體驗上來講,這點是很是差的,因而想到dwr和websocket實現實時消息推送瀏覽器,前者是一個用於改善web頁面與Java類交互的遠程服務器端Ajax開源框架,它能夠容許在瀏覽器裏的代碼使用運行在WEB服務器上的JAVA方法,就像它就在瀏覽器裏同樣,但存在必定的java代碼泄露風險,然後者是一種網絡雙工通信TCP協議,長鏈接,須要客戶端發起鏈接。二者實現起來都是相對比較簡單的,下面來簡單實現下dwr!javascript

實現步驟以下:html

一、maven引jar   java

<dependency>
   <groupId>org.directwebremoting</groupId>
   <artifactId>dwr</artifactId>
   <version>3.0.2-RELEASE</version>
</dependency>

二、dwr無xml配置部分web

package com.paic.commcc.support.dwr;

import org.directwebremoting.Container;
import org.directwebremoting.create.NewCreator;
import org.directwebremoting.extend.Configurator;
import org.directwebremoting.extend.CreatorManager;

/**
 * @author 
 * @Package com.paic.commcc.support.dwr
 * @Description: dwr的xml配置
 * @date 2018/12/11 19:19
 */
public class DwrXml implements Configurator {

    @Override
    public void configure(Container container) {
        CreatorManager creatorManager = container.getBean(CreatorManager.class);
        NewCreator creator = new NewCreator();
        creator.setClass("com.paic.commcc.support.dwr.DwrPush");
        creator.setJavascript("DwrPush");
        creatorManager.addCreator(creator);
    }

}

三、dwr核心配置,注意標色代碼部分是第2點的配置類路徑ajax

package com.paic.commcc.support.dwr;

import org.directwebremoting.servlet.DwrListener;
import org.directwebremoting.servlet.DwrServlet;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 
 * @Package com.paic.commcc.support.dwr
 * @Description: 遠程服務端ajax
 * @date 2018/12/11 19:17
 */
@Configuration
public class DwrConfig {
    @Bean
    public ServletRegistrationBean dwr() {
        ServletRegistrationBean servlet = new ServletRegistrationBean(new DwrServlet(), "/dwr/*");
        Map<String, String> initParam = new HashMap<>();
        initParam.put("crossDomainSessionSecurity", "false");
        initParam.put("allowScriptTagRemoting", "true");
        initParam.put("classes", "java.lang.Object");
        initParam.put("activeReverseAjaxEnabled", "true");
        initParam.put("initApplicationScopeCreatorsAtStartup", "true");
        initParam.put("maxWaitAfterWrite", "60000");
        initParam.put("debug", "true");
        initParam.put("logLevel", "WARN");
        //自定義配置,org.directwebremoting.impl.StartupUtil#configureFromInitParams name.equals("customConfigurator")
        //DwrServlet#init 初始化this.container
        initParam.put("customConfigurator", "com.paic.commcc.support.dwr.DwrXml");
        servlet.setInitParameters(initParam);
        return servlet;
    }

    @Bean
    public ServletListenerRegistrationBean dwrListener() {
        return new ServletListenerRegistrationBean(new DwrListener());
    }

}

四、dwr推送消息類spring

package com.paic.commcc.support.dwr;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ScriptSessions;

/**
 * @author 
 * @Package com.paic.commcc.support.dwr
 * @Description: dwr推送消息類
 * @date 2018/12/11 19:23
 */
public class DwrPush {

    public static void init(String msg) {
        DwrPush.sendMsgToPage("/dwr.html", msg);
    }

    /**
     * @Description: 推送消息至頁面,默認onDwrData函數
     * @Param: [html, msg]
     * @return: void
     * @Author: 
     * @Date: 2018/12/12
     */
    public static void sendMsgToPage(final String html, final String msg) {
        sendMsgToPage(html, "onDwrData", msg);
    }

    public static void sendMsgToPage(final String html, final String function, final String msg) {
        Browser.withPage(html, new Runnable() {
            public void run() {
                ScriptSessions.addFunctionCall(function, msg);
            }
        });
    }

    public static void sendMsgWithAllSessions(final String msg) {
        Browser.withAllSessions(new Runnable() {
            public void run() {
                ScriptSessions.addFunctionCall("onDwrData", msg);
            }
        });
    }

    public static void sendMsgWithFilter(final String msg) {
        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
            @Override
            public boolean match(ScriptSession scriptSession) {
                // 能夠在這裏作一些session過濾
                return true;
            }
        }, new Runnable() {
            public void run() {
                ScriptSessions.addFunctionCall("onDwrData", msg);
            }
        });
    }
}

五、dwr.html頁面放static目錄下,3個js,其中DwrPush.js的名字跟推送消息類一致,其餘兩個爲框架自己的,必需要引用瀏覽器

<html>
<head>
    <title>dwr html</title>
    <script type='text/javascript' src='/dwr/engine.js'></script>
    <script type='text/javascript' src='/dwr/interface/DwrPush.js'></script>
    <script type='text/javascript' src='/dwr/util.js'></script>

    <script>
        window.onload = function () {
            dwr.engine.setActiveReverseAjax(true);//開啓反向ajax
            dwr.engine.setNotifyServerOnPageUnload(true);//頁面關閉通知服務器銷燬當前會話scriptsession
            dwr.engine.setErrorHandler(function(msg) {
                alert(msg);
            });
            DwrPush.init("dwr hello");
        }
        function onDwrData(data) {
            alert(data);
        }
    </script>
</head>
<body>

dwr html
</body>
</html>

而後就能夠實現後臺有節點狀態變動時,調用dwr消息推送類刷新瀏覽器節點狀態了,怎麼去刷新就看具體實現。服務器

但願對你有所幫助,謝謝~websocket

相關文章
相關標籤/搜索