springboot 整合dwr实现消息推送

加入依赖

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

配置文件中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">

    <dwr:annotation-config/>
    <dwr:annotation-scan base-package="com.example.core.dwr" scanDataTransferObject="true" scanRemoteProxy="true"/>
    <dwr:configuration />
</beans>

DwrScriptSessionManagerUtil


package com.example.core.dwr;

import org.directwebremoting.Container;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;
import org.directwebremoting.servlet.DwrServlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

/**
 * 2018-06-25
 * author MWF
 */
public class DwrScriptSessionManagerUtil extends DwrServlet {
    public void init() throws ServletException {

        Container container = ServerContextFactory.get().getContainer();

        ScriptSessionManager manager = container .getBean(ScriptSessionManager.class);

        ScriptSessionListener listener = new ScriptSessionListener() {

            public void sessionCreated(ScriptSessionEvent ev) {

                HttpSession session = WebContextFactory.get().getSession();

                String userId = (String) session.getAttribute("userId");

                System.out.println("a ScriptSession is created!");

                ev.getSession().setAttribute("userId", userId);

            }

            public void sessionDestroyed(ScriptSessionEvent ev) {

                System.out.println("a ScriptSession is distroyed");

            }

        };

        manager.addScriptSessionListener(listener);

    }
}

MessagePush类
package com.example.core.dwr;

import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

import javax.servlet.ServletException;

@RemoteProxy(name = "MessagePush")
public class MessagePush {
    @RemoteMethod
    public void onPageLoad(String userId) {

        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();

        scriptSession.setAttribute("userId", userId);

        DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();

        try {

            dwrScriptSessionManagerUtil.init();

        } catch (ServletException e) {

            e.printStackTrace();

        }

    }
}

页面代码

<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="${pageContext.request.contextPath }/task/js/jquery.min.js"></script>
    <script type='text/javascript' src='../dwr/engine.js'></script>
    <script type="text/javascript" src="../dwr/util.js"></script>
    <script type='text/javascript' src='../dwr/interface/MessagePush.js'></script>
    <%--<script type='text/javascript' src='../dwr/interface/MessageServiceImpl.js'></script>--%>
</head>

<body οnlοad="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);onPageLoad()">
<input id="data" > <button id="button">button</button>
<p id="p">


</p>
</body>


<script>
    function onPageLoad(){
        MessagePush.onPageLoad(1);
    }

    function showMessage(msg) {
        //接受消息
        $("#p").append(msg + "<br>")
    }
    $(function () {
        //发送消息
        $("#button").click(function(){
            // 此类即为根据java文件生成的js文件
            var data = document.getElementById("data").value;
            $.ajax({
                    url : "${pageContext.request.contextPath}/message/msg",
                    type : "GET",
                    data: {string:data},
                    success : function(checkMap) {
                      console(checkMap)
                    }
                });
        });
    })

</script>
</html>

启动类中注入bean

package com.example;

import com.sun.org.apache.bcel.internal.util.ClassPath;
import net.sf.ehcache.CacheManager;
import org.directwebremoting.spring.DwrSpringServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import net.sf.ehcache.constructs.web.ShutdownListener;
import org.springframework.context.annotation.ImportResource;

import javax.servlet.MultipartConfigElement;
import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@ImportResource(locations = "dwr-spring-config.xml")
public class WeixinTestApplication {

    public static void main(String[] args) {
    	System.setProperty("net.sf.ehcache.enableShutdownHook", "true");
        SpringApplication.run(WeixinTestApplication.class, args);
    }

    
    /**
     * dwr消息推送
     * @return
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        DwrSpringServlet servlet = new DwrSpringServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(servlet, "/dwr/*");
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("debug", "true");
        initParameters.put("activeReverseAjaxEnabled","true");
        /*initParameters.put("pollAndCometEnabled","true");
        initParameters.put("crossDomainSessionSecurity","false");
        initParameters.put("allowScriptTagRemoting","true");*/
        registrationBean.setInitParameters(initParameters);
        return registrationBean;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值