You can describe the implementation process of dwr message push.
First, add dwr. jar to the project, and then configure the following code in web. xml:
<servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/config/dwr.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>crossDomainSessionSecurity</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>allowScriptTagRemoting</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>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>3000</param-value> </init-param> <init-param> <param-name>logLevel</param-name> <param-value>WARN</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
We can see from the configuration that a dwr configuration file needs to be created, as shown below:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr//dwr30.dtd"><dwr> <allow> <!-- <create javascript="udao" creator="spring"> <param name="beanName" value="udao" /> <include method="getUserPage"/> </create> <convert converter="bean" match="com.cpsoft.app.web.domain.PageModel" /> --> <create javascript="MessagePush" creator="spring"> <param name="beanName" value="messagePush" /> </create> <convert converter="bean" match="java.lang.StackTraceElement" /> <convert converter="exception" match="java.lang.Exception" /> </allow></dwr>
As you can see, I have configured a messagePush object, so let me talk about this object.
@ Componentpublic class MessagePush {final public static String SCRIPT_SESSION_USERID = "SCRIPT_SESSION_USERID"; final public static String SCRIPT_SESSION_MSG = "showMessage"; // when the page is pushed by background messages, name of the automatically triggered js method private Logger log = Logger. getLogger (this. getClass (); private ScriptSessionListener listener; private boolean isInit = false; public boolean isInit () {return isInit;}/*** get the listening object of scriptSession, You only need to instantiate it once * @ return */public ScriptSessionListener getListener () {if (listener = null) {listener = new ScriptSessionListener () {public void sessionCreated (ScriptSessionEvent ev) {HttpSession session = WebContextFactory. get (). getSession (); Staff staff = SessionUtil. getStaff (session); if (staff! = Null) {ev. getSession (). setAttribute (SCRIPT_SESSION_USERID, staff. getId (); // log.info ("a ScriptSession [" + staff. getId () + "] is created! "); Map <String, Staff> onlineStaffMap = CacheUtil. getOnlineStaffMap (); // obtain the current online user if (! OnlineStaffMap. containsKey (staff. getId () onlineStaffMap. put (staff. getId (), staff); // Add the current user to the cache if (! IsInit) isInit = true;} public void sessionDestroyed (ScriptSessionEvent ev) {String userId = (String) ev. getSession (). getAttribute (SCRIPT_SESSION_USERID); log.info ("a ScriptSession [" + userId + "] is distroyed! ") ;}}}Return listener;}/*** initialize the dwr listener and only call it once in the Program */public void init () {if (listener = null) {Container container = ServerContextFactory. get (). getContainer (); ScriptSessionManager manager = container. getBean (ScriptSessionManager. class); manager. addScriptSessionListener (getListener (); log.info ("the dwr client is inited! ");}}}
The main function of this class is to initialize the listener. If there is a listener, the message can be pushed now. Please refer to the code.
/*** Use dwr to push messages to the foreground * @ param userId user ID * @ param autoMessage message content */private static void sendMessageAuto (final String userId, final String autoMessage) {Browser. withAllSessionsFiltered (new ScriptSessionFilter () {public boolean match (ScriptSession session) {String id = (String) session. getAttribute (MessagePush. SCRIPT_SESSION_USERID); if (id = null |! UserId. equals (id) {// match the recipient's Id return false;} return true ;}}, new Runnable () {private ScriptBuffer script = new ScriptBuffer (); public void run () {script. appendCall (MessagePush. SCRIPT_SESSION_MSG, autoMessage); // push messages (here I use a json string) Collection <ScriptSession> sessions = Browser. getTargetSessions (); // obtain the current target client object for (ScriptSession scriptSession: sessions) {scriptSession. addScript (script );}}});}
Speaking of this, the background work has come to an end. Let's talk about the front-end, first introduce js.
<! -- Message push --> <script type = 'text/javascript 'src =' $ {ctx}/dwr/engine. js'> </script> <script type = 'text/javascript 'src =' $ {ctx}/dwr/util. js'> </script> <script type = "text/javascript" src = "$ {ctx}/dwr/interface/MessagePush. js "> </script>
Add in onload
<body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);">
Now the big work is complete. As long as the above push method is called in the background, the foreground will automatically trigger
Function showMessage (autoMessage) {// alert (autoMessage); if (! CallCometShowMsg) {eval ("var json =" + autoMessage); g_showTip ("Message Type:" + json. MESSAGE_TYPE + "<br/> message content:" + json. MESSAGE_DATA);} else {callCometShowMsg (autoMessage );}}
Finally, let's make a summary. After a test, we found that the response in Ie8 was a little slower. For chrome, the version I used may have problems and Firefox was doing well.
If you have any questions, please leave a message and you will be able to reply immediately.