SPRINGMVC+DWR3 implementation of accurate push information (2 methods)

Source: Internet
Author: User
Tags sessions

SPRINGMVC+DWR3 implementation message accurate push (annotation way + file way)

This article assumes that the SPRINGMVC configuration is complete and that the configuration is added above the SPRINGMVC configuration. Since some of these principles are not yet understood, the configuration for each one does not explain why

DWR3 is downloading the latest from the DWR official website. Http://directwebremoting.org/dwr/index.html

Method 1: (This method may not be able to push the message on the first open page, unexplained)

File mode:

1 A, add the DWR configuration inside the Web.xml , as follows:

		
<servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class> Org.directwebremoting.servlet.dwrservlet</servlet-class> <init-param> <param-name>debug</ param-name> <param-value>true</param-value> </init-param> <init-param> <param-na Me>activereverseajaxenabled</param-name> <param-value>true</param-value> </init-param > <init-param> <param-name>pollAndCometEnabled</param-name> <param-value>true</par am-value> </init-param> <init-param> &LT;PARAM-NAME&GT;CROSSDOMAINSESSIONSECURITY&LT;/PARAM-NAME&G
    T <param-value>false</param-value> </init-param> <init-param> <param-name>allowscript tagremoting</param-name> <param-value>true</param-value> </init-param> <load-on-startu P>1</load-on-startup> </servlet> <servleT-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
1 B, the establishment of dwr.xml in the Web.xml-level directory

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE dwr public
    "-//getahead limited//dtd Direct Web Remoting 3.0//en"
    "http://directwebremoting.org/ Schema/dwr30.dtd ">
<dwr>
	<allow>
		<create javascript=" Messagepush "creator=" new " >
			<param name= "class" Value= "Com.arch.web.dwr.MessagePush" ></param>
		</create>
	</allow>
</dwr>
One of the Com.arch.web.dwr.MessagePush, is my message push registration class.

1 C, the establishment of Messgepush class , the specific categories are as follows

public class Messagepush {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 ()}

		}
}
Open Onpageload method for pre-section page registration call

1D, Messagepush need Dwrscriptsessionmanagerutil, the establishment of dwrscriptsessionmanagerutil content is as follows:

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) { C5/>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);

	}

1E, pre-paragraph page

Introduction of Dwr Core JS

<script type= "Text/javascript" src= "<%=basepath%>dwr/engine.js" ></script> <!-- BasePath: Website Basic roadbed-->
<script type= "Text/javascript" src= "<%=basepath%>dwr/util.js" ></script >

Introduce message Registration JS

<script type= "Text/javascript" src= "<%=basepath%>dwr/interface/calltest.js" ></script>

Set up registration JS and receive Message JS

function Onpageload () {
	var userId = ' ${userid} ';
	Messagepush.onpageload (userId);
}

function ShowMessage (msg) {
	alert (dwr.util.toDescriptiveString (data)); 
}

Add onload attribute information to the Body tab of the page

<body onload= "Dwr.engine.setActiveReverseAjax (True);d wr.engine.setNotifyServerOnPageUnload (true); Onpageload ( );" >

1F, now you need a push message method to send our push message to a specific user (just put it in a class)

public static void Sendmessageauto (string userid, String message) {

		final String userid = userid;

		Final String automessage = message;
		Final String op_id = "UserId";
		
		Browser.withallsessionsfiltered (New Scriptsessionfilter () {public

			Boolean match (scriptsession session) {
				if (Session.getattribute (op_id) = null)
					return false;
				else {
					Boolean f = Session.getattribute (op_id). Equals (userId);
					return f;
				}
			}

		, New Runnable () {

			private Scriptbuffer script = new Scriptbuffer ();

			public void Run () {

				script.appendcall ("ShowMessage", automessage);
				collection<scriptsession> sessions = Browser.gettargetsessions ();
				for (Scriptsession scriptsession:sessions) {
					scriptsession.addscript (script);}}}

		);

	
These are all configured, and you can now use Sendmessageauto to push messages to the specified user

Annotation method:

Annotations are in fact similar to the way they are documented and need to be modified in the following places:

1, in (1 a) step, no longer web.xml inside configuration dwr, but in Springmvc file configuration Dwr, specific configuration as follows

	<!--dwr configuration--> <bean class= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> < Dwr:annotation-scan base-package= "COM.CB" scandatatransferobject= "true"/> <dwr:configuration/> <dwr: Annotation-config id= "dwr"/> <dwr:url-mapping/> <dwr:controller id= "Dwrcontroller" debug= "true" > < Dwr:config-param name= "allowscripttagremoting" value= "true"/> <dwr:config-param " Crossdomainsessionsecurity "value=" false "/> <dwr:config-param name=" activereverseajaxenabled "value=" true " /> <dwr:config-param name= "pollandcometenabled" value= "true"/> <dwr:config-param "name=" Emoting "value=" true "/> </dwr:controller> <bean class=" Org.springframework.web.servlet.mvc.annotatio N.defaultannotationhandlermapping "> <property name=" Order "value=" 1 "/> </bean> <bean clas S= "Org.springframework.web.servlet.handler.BeanNameUrlHandleRmapping "> <property name=" Order "value=" 2 "/> </bean> <bean class=" Org.springframework.web . servlet.handler.SimpleUrlHandlerMapping "> <property name=" Order "value=" 3 "/> <property" true "nam E= "Alwaysusefullpath" ></property> <property name= "Mappings" > <props> <prop key= "/dwr/**" & gt;dwrcontroller</prop> </props> </property> </bean>
2, do not need dwr.xml configuration file, omitted ( 1 B) Step

3. In (1D) step, add annotation to Messagepush class

@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 ()}

		}
}
The other does not change.

Note: This method may not create a session when the page is first opened, resulting in the inability to push the message, but the page refreshes. (Why is this specific reason has not been found)


Method 2:

In order to resolve the problem of the first opening that appears in Method 1, the practice here is to automatically create scriptsession each time a user opens a page that needs to be pushed, and simply assume that the DWR page needs to be pushed (which, of course, can be modified according to its own business). Implementation of specific page push exactly)

File mode:

2 A, first need to create their own session management class , here is the name: Com.toolbox.util.DwrScriptSessionManagerUtil

public class Dwrscriptsessionmanagerutil extends defaultscriptsessionmanager{private final Logger Logger = LOGGERFAC
	Tory.getlogger (This.getclass ());
	private static final String ss_id = "dwr_scriptsession_id";

	
	private static final String op_id = "UserId"; Public Dwrscriptsessionmanagerutil () {addscriptsessionlistener, new Scriptsessionlistener () {public void session
	    		 
                    Created (scriptsessionevent ev) {logger.info ("script session in ...");
                    HttpSession HttpSession = Webcontextfactory.get (). GetSession ();
                    
                    Scriptsession scriptsession = Ev.getsession ();
					String userId = (string) httpsession.getattribute ("UserId");
						if (userId = = null) {Logger.info ("script session Invalidate");
						Scriptsession.invalidate ();
						Httpsession.invalidate ();
					Return
//There is already an old scriptsession logoff this old scriptsession defaultscriptsession = Sessionmap.get (userId);					if (old!= null) {DwrScriptSessionManagerUtil.this.invalidate);

					} httpsession.setattribute (ss_id, Scriptsession.getid ());
					Scriptsession.setattribute (op_id, userId);
					Scriptsession.setattribute ("SESSIONID", Httpsession.getid ());
	             Logger.info ("script session created:" + userId); } public void sessiondestroyed (Scriptsessionevent ev) {scriptsession SS = Ev.getsessi
	  				On ();
	  				if (Ss.getattribute (op_id)!= null) {Logger.info ("script session Destroyed:" + ss.getattribute (op_id));
		
		}
	             }
	      });
	This.setscriptsessiontimeout (150000L); }
2 B, add our session management class to the DWR controller

<servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class> Org.directwebremoting.servlet.dwrservlet</servlet-class> <init-param> <param-name> Org.directwebremoting.extend.scriptsessionmanager</param-name> <param-value> com.toolbox.util.dwrscriptsessionmanagerutil</param-value> </init-param> <init-param> <param -name>debug</param-name> <param-value>true</param-value> </init-param> <init-param&
    Gt <param-name>activeReverseAjaxEnabled</param-name> <param-value>true</param-value> </ init-param> <init-param> <param-name>pollAndCometEnabled</param-name> <param-value>tr ue</param-value> </init-param> <init-param> <param-name>crossdomainsessionsecurity</pa ram-name> <param-value>false</param-value> </init-param> <init-param> <param-name>allowScriptTagRemoting</param-name> <param-value>true</param-value> </ init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> < Servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </ Servlet-mapping>
2 C, the WEB.XNL in the same directory to create an empty dwr.xnl file
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE dwr public
    "-//getahead limited//dtd Direct Web Remoting 3.0//en"
    "http://directwebremoting.org/ Schema/dwr30.dtd ">
<dwr>
	<allow>
	</allow>
</dwr>
2D, front page

<script type= "Text/javascript" src= "<%=basepath%>dwr/engine.js" ></script> <!-- BasePath: Website Basic roadbed-->
<script type= "Text/javascript" src= "<%=basepath%>dwr/util.js" ></script >
function ShowMessage (msg) {
	alert (dwr.util.toDescriptiveString (data)); 
}
<body onload= "Dwr.engine.setActiveReverseAjax (True);d wr.engine.setNotifyServerOnPageUnload (true); >
This is because the backend assumes that if you use DWR, you will need to push the message, so the money-side does not need to invoke the message registration operation

2E, message sending method

public static void Sendmessageauto (string userid, String message) {

		final String userid = userid;

		Final String automessage = message;
		Final String op_id = "UserId";
		
		Browser.withallsessionsfiltered (New Scriptsessionfilter () {public

			Boolean match (scriptsession session) {
				if (Session.getattribute (op_id) = null)
					return false;
				else {
					Boolean f = Session.getattribute (op_id). Equals (userId);
					return f;
				}
			}

		, New Runnable () {

			private Scriptbuffer script = new Scriptbuffer ();

			public void Run () {

				script.appendcall ("ShowMessage", automessage);
				collection<scriptsession> sessions = Browser.gettargetsessions ();
				for (Scriptsession scriptsession:sessions) {
					scriptsession.addscript (script);}}}

		);

	
It's all over here. The front section is now receiving a push message normally

Annotation Method:

The annotations are much more convenient here, and the steps in method 1 similar to those that need to be changed are:

· 1,(2B) does not need to configure the Dwr,dwr configuration in the Web.xml in the SPRINGMVC

<bean class= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <dwr:annotation-scan Base-package= "COM.CB" scandatatransferobject= "true"/> <dwr:configuration/> <dwr:annotation-config id= " Dwr "/> <dwr:url-mapping/> <dwr:controller id=" Dwrcontroller "true" > debug= <dwr:config-param "Allowscripttagremoting" value= "true"/> <dwr:config-param name= "crossdomainsessionsecurity" value= "false"/ > <dwr:config-param name= "activereverseajaxenabled" value= "true"/> <dwr:config-param "name=" Ebremoting.extend.ScriptSessionManager "value=" Com.toolbox.util.DwrScriptSessionManagerUtil "/> <dwr: Config-param name= "pollandcometenabled" value= "true"/> <dwr:config-param name= "allowscripttagremoting" Valu E= "true"/> </dwr:controller> <bean class= " Org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping "> <property name=" intErceptors "> <list> <bean class=" Com.arch.interceptor.AclInterceptorAdapter "/> </list> &l t;/property> <property name= "Order" value= "1"/> </bean> <bean class= "org.springframework. Web.servlet.handler.BeanNameUrlHandlerMapping "> <property name=" Order "value=" 2 "/> </bean> &l T;bean class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name= "Order" value
			= "3"/> <property value= "true" Name= "Alwaysusefullpath" ></property> <property name= "Mappings" > <props> <prop key= "/dwr/**" >dwrController</prop> </props> </property> &LT;/BEAN&G T

2, do not dwr.xml configuration file, so skip (2C)

The other steps do not change.

This DWR3 message push to build the completion.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.