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

}

代码如下,请大家指点一下 dwr.xml [code="java"] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd"> <dwr> <allow> <create creator="spring" javascript="Hello" > <param name="beanName" value="Hello"></param> <param name="location" value="applicationContext.xml"></param> </create> </allow> </dwr> [/code] web.xml [code="java"] <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>classes</param-name> <param-value>java.lang.Object</param-value> </init-param> <init-param> <param-name>logLevel</param-name> <param-value>INFO</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext-*.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> [/code] applicationContext.xml [code="java"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="Hello" class="com.zscqj.common.Hello"> </bean> </beans> [/code] jsp [code="java"] <script src='dwr/interface/Hello.js'></script> <script src='dwr/engine.js'></script> <script type='text/javascript' src='dwr/util.js'></script> </head> <script language="javascript"> function tijiao() { var info=document.all["infor"].value; alert(info); Hello.say(info,callback); } function callback(data) { document.all["con"].innerHTML=data; } </script> <body> <center> <input type="text" name="infor"> <input type="button" value="看看我" onclick="tijiao()"><br> 提交后返回的内容如下: <br><font color="red"> <span id="con"></span> </font> </center> </body> </html> [/code] 如果我用new的话就没有任何问题,而spring就不可以,感觉的是bean容器未被引用,可是我在web中已经添加了监听器,监听器是没有问题了,不知道为什么会这样~
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页