功能需求:

有一个系统,当我们登录成功后,跳转到success.jsp页面。多人登录,每个人都会停留在这个页面。此事,我只想给一个账号叫aaa的人的success.jsp页面推送信息;其他人的success.jsp接收不到。

思路:

当一个页面调用dwr生成的js时,会产生一个scriptSession。类似与session,是一个唯一标示符。根据这个scriptSession我们可以知道到底要推给哪一个页面。鉴于此:

1.在登录的时候,我们将登录的人的信息放入到session里面(这里是session,而不是scriptSession);这一步是在login.jsp页面提交后跳转到loginAction里面实现。

2.在登录成功后,加载success.jsp页面时,我们出发一个dwr生成的js里面的方法,此事产生一个scriptSession,我们将session中的个人信息取出来,将用户名存入scriptSession中;

3.在发送页面,push.jsp;当我们点击发送时,遍历所有的scriptSession,在scriptSession找到用户名,推送。

代码目录:

具体代码:

<span style="font-size:14px;">public class User {
	private String name;
	private String password;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getpassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}</span>

下面定义管理器和监听器:

<span style="font-size:14px;">public class DwrScriptSessionManagerUtil extends DefaultScriptSessionManager {

	 private static final long serialVersionUID = -7504612622407420071L;
	 
	 public DwrScriptSessionManagerUtil(){
		 System.out.println("正在启动scriptSessionManager...");
		 this.addScriptSessionListener(new DwrScriptSessionListener());
	 }
		
}
</span>

<span style="font-size:14px;">public class DwrScriptSessionListener implements ScriptSessionListener{
//	public static final List list = new ArrayList<Map>();
	@Override
	public void sessionCreated(ScriptSessionEvent event) {
		// Todo Auto-generated method stub\
		System.out.println("create a new scriptSession");
		 WebContext context = WebContextFactory.get();
		 HttpSession session = context.getSession();
		 ScriptSession scriptSession = event.getSession();
		 System.out.println(scriptSession.getId());
		 //session中的username放入到scriptSession中
		 scriptSession.setAttribute("username",((User)session.getAttribute("user")).getName());
	}

	@Override
	public void sessionDestroyed(ScriptSessionEvent arg0) {
		// Todo Auto-generated method stub
		System.out.println("destroy the old scriptSession");
		 WebContext context = WebContextFactory.get();
		 HttpSession session = context.getSession();
	}

}</span>

登录:

<span style="font-size:14px;">public class Login  extends HttpServlet {

	public void doGet(HttpServletRequest request,HttpServletResponse response)
			throws servletexception,IOException {
		this.doPost(request,response);
	}

	public void doPost(HttpServletRequest request,IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
		HttpSession session = request.getSession();
		User user = new User();
		user.setName(username);
		user.setPassword(password);
		session.setAttribute("user",user);
		response.sendRedirect("success.jsp");
	}
<span style="font-size:18px;">}</span></span>

推送:

<span style="font-size:14px;">public class PushMessage {
	
	public void pushMessage(String name,String content){
		System.out.println("准备发送消息");
		final String username = name;
		final String autoMessage  = content;
		WebContext context = WebContextFactory.get();
		browser.withAllSessionsFiltered(new ScriptSessionFilter(){

			public boolean match(ScriptSession session) {
				//这里判断session里面保存的用户信息,获取scriptSession的情况
				if(username.equals((String)session.getAttribute("username")))
					return true;
				return false;
					
			}
		},new Runnable(){
			private ScriptBuffer script = new ScriptBuffer(); 
			@Override
			public void run() {
				// Todo Auto-generated method stub
					script.appendCall("showMessage",autoMessage);
				   Collection<ScriptSession> sessions = browser.getTargetSessions();
				   for (ScriptSession scriptSession : sessions){  
	                    scriptSession.addScript(script);  
	                }  
			}
			
		});
	}
}</span>

<span style="font-size:14px;">public class InitRecieve {
	
	
	public void initMessage(String username){
		System.out.println("初始化将要显示推送信息的页面");
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute("username",username);
		System.out.println(scriptSession.getId());
		HttpSession session = WebContextFactory.get().getSession();
		System.out.println(((User)session.getAttribute("user")).getName());
	}

}</span>

配置文件:

web.xml

<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  
  <listener>
  	<listener-class>org.directwebremoting.servlet.DwrListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dwr</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-name>crossDomainSessionSecurity</param-name>
      <param-value>false</param-value>
    </init-param>
    <!-- 解决找不到注释类产生的报错 -->
       <init-param>
          <param-name>classes</param-name>
          <param-value>java.lang.Object</param-value>
        </init-param>
        <!-- 启动逆ajax,也就是推 -->
        <init-param>
            <param-name>activeReverseAjaxEnabled</param-name>
            <param-value>true</param-value>
        </init-param>
        <!-- 启动自定义管理scriptSession -->
        <init-param>
        	<param-name>org.directwebremoting.extend.ScriptSessionManager</param-name>
        	<param-value>com.mz.dwr.DwrScriptSessionManagerUtil</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>
  </servlet>
  <servlet-mapping>
    <servlet-name>dwr</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>
  
  <servlet>
		<servlet-name>LoginAction</servlet-name>
		<servlet-class>com.mz.action.Login</servlet-class>
  </servlet>

	<servlet-mapping>
		<servlet-name>LoginAction</servlet-name>
		<url-pattern>/login.do</url-pattern>
	</servlet-mapping>
</web-app></span>

dwr.xml

<span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd">
<!-- 通用dwr配置 -->
<dwr>
<allow>
	<!-- 建立JS对象,将目标对象的方法转换成JS对象的方法 -->
	<create creator="new" javascript="initRecieve" >
		<param name="class" value="com.mz.action.InitRecieve"></param>
	</create>
	
	<create creator="new" javascript="pushMessage">
		<param name="class" value="com.mz.action.PushMessage"></param>
	</create>
</allow>
</dwr></span>

JSP页面:

login.jsp

<span style="font-size:14px;"><%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getcontextpath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<Meta http-equiv="pragma" content="no-cache">
	<Meta http-equiv="cache-control" content="no-cache">
	<Meta http-equiv="expires" content="0">    
	<Meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<Meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
  <form action="login.do" method="post">
    <input type="text" id="username" name="username"><br/>
    <input type="password" id="password" name="passoword"><br/>
    <input type="submit"  value="send"/>
    </form>
  </body>
</html></span>
success.jsp

<span style="font-size:14px;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getcontextpath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<Meta http-equiv="pragma" content="no-cache">
	<Meta http-equiv="cache-control" content="no-cache">
	<Meta http-equiv="expires" content="0">    
	<Meta http-equiv="keywords" content="keyword1,keyword3">
	<Meta http-equiv="description" content="This is my page">
	<script type='text/javascript' src='${pageContext.request.contextpath}/dwr/engine.js'></script>  
        <script type='text/javascript' src='${pageContext.request.contextpath}/dwr/util.js'></script>  
  <!--在线jquery库-->      <script type='text/javascript' src='${pageContext.request.contextpath}/dwr/interface/initRecieve.js'></script>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script type="text/javascript">
		function init(){
			//开启推送
			dwr.engine.setActiveReverseAjax(true);
			//销毁或刷新页面时销毁当前ScriptSession
			dwr.engine.setNotifyServerOnPageUnload(true);
			//服务器关闭,取消dwr弹的错误提示框
			dwr.engine.setErrorHandler(function(){});
		}
		
		function onPageLoad(){
			initRecieve.initMessage('${user.name}');
		}
		
		 function showMessage(autoMessage){  
			alert("s");
			  $("#show").text(autoMessage);  
		 }
	</script>
  </head>
  
  <body onload="init(); onPageLoad();">
   <div id="show"></div>
  </body>
</html></span>

push.jsp

<span style="font-size:14px;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getcontextpath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<Meta http-equiv="pragma" content="no-cache">
	<Meta http-equiv="cache-control" content="no-cache">
	<Meta http-equiv="expires" content="0">    
	 <script type='text/javascript' src='${pageContext.request.contextpath}/dwr/engine.js'></script>  
    <script type='text/javascript' src='${pageContext.request.contextpath}/dwr/util.js'></script>  
    <script type='text/javascript' src='${pageContext.request.contextpath}/dwr/interface/pushMessage.js'></script>  
    <script type="text/javascript">
	function init(){
		//开启推送
		//销毁或刷新页面时销毁当前ScriptSession
		dwr.engine.setNotifyServerOnPageUnload(true);
		//服务器关闭,取消dwr弹的错误提示框
	}
    function test() {  
        var username = document.getElementById("username").value;  
        var content = document.getElementById("content").value;
        //msg = {msgid: '1',context: $("#msgContext").val()};  
        pushMessage.pushMessage(username,content);  
   //     location.reload();
          
    }  
    </script>
  </head>
  
  <body >
    username : <input type="text" name="username" id="username" /> <br />  
      <input type="text" id="content"/>
    <input type="button" value="Send" onclick="test()"  />  
   
  </body>
</html></span>

测试方法:

启动项目后,打开多个login.jsp;任意输入账号密码;

打开push.jsp; 输入刚才登录的其中一个账号;并且输出内容;查看变化。

问题:

上面说了,每当调用页面里面由dwr产生的js时都会创建一个scriptSession,所以在发送发送消息是,会发现多产了一个ScriptSession.由于我是在后台Quartz不断调度任务进行推的。所以没有用到页面推送,也就没解决这个问题。但是我觉的,在发送后立即刷新页面应该是一个解决方法。


代码打包,附上连接:

DWR的精确推送的更多相关文章

  1. HTML5 Web缓存和运用程序缓存(cookie,session)

    这篇文章主要介绍了HTML5 Web缓存和运用程序缓存(cookie,session),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. iOS Swift上弃用后Twitter.sharedInstance().session()?. userName的替代方案

    解决方法如果您仍在寻找解决方案,请参阅以下内容:

  3. 使用Fabric SDK iOS访问Twitter用户时间线

    我试图在这个问题上挣扎两天.我正在使用FabricSDK和Rest工具包,试图为Twitter使用不同的RestAPIWeb服务.我可以使用具有authTokenSecret,authToken和其他值的会话对象的TWTRLogInButton成功登录.当我尝试获取用户时间线时,我总是得到失败的响应,作为:{“errors”:[{“code”:215,“message”:“BadAuthentic

  4. ios – 如何从Apple Watch调用iPhone上定义的方法

    有没有办法从Watchkit扩展中调用iPhone上的类中定义的方法?根据我的理解,目前在Watchkit和iPhone之间进行本地通信的方法之一是使用NSUserDefaults,但还有其他方法吗?

  5. ios – 如何将视频从AVAssetExportSession保存到相机胶卷?

    在此先感谢您的帮助.解决方法只需使用session.outputURL=…

  6. ios – 使用AVCaptureSession sessionPreset = AVCaptureSessionPresetPhoto拉伸捕获的照片

    解决方法所以我解决了我的问题.这是我现在使用的代码,它工作正常:…重要的输出imagaView:一些额外的信息:相机图层必须是全屏,并且outputimageView也必须是.我希望这些对某些人来说也是有用的信息.

  7. 我可以在iOS中自定义Twitter工具包的登录按钮吗?

    我已经下载了Twitter工具包框架并添加了用Twitter登录的代码.但是,我不希望登录按钮看起来像那样.我想要一个用于登录的自定义按钮.我能这样做吗?我只想使用这个框架,因为这也适用于iOS系统帐户.解决方法根据document:在按下按钮中添加代码:Objective-C的迅速

  8. ios – AVCaptureSession条形码扫描

    解决方法以下是我所拥有的项目代码示例,可以帮助您走上正确的轨道

  9. ios – 如何在Watch OS 2中引用不支持的框架

    有没有办法将框架链接到扩展名?

  10. ios7 – 在iOS 7中设置Alamofire中的自定义HTTP标头不工作

    解决方法我得到它的工作这对iOS7没有影响:然而,这将适用于iOS7和8:

随机推荐

  1. xe-ajax-mock 前端虚拟服务

    最新版本见Github,点击查看历史版本基于XEAjax扩展的Mock虚拟服务插件;对于前后端分离的开发模式,ajax+mock使前端不再依赖后端接口开发效率更高。CDN使用script方式安装,XEAjaxMock会定义为全局变量生产环境请使用xe-ajax-mock.min.js,更小的压缩版本,可以带来更快的速度体验。

  2. vue 使用 xe-ajax

    安装完成后自动挂载在vue实例this.$ajaxCDN安装使用script方式安装,VXEAjax会定义为全局变量生产环境请使用vxe-ajax.min.js,更小的压缩版本,可以带来更快的速度体验。cdnjs获取最新版本点击浏览已发布的所有npm包源码unpkg获取最新版本点击浏览已发布的所有npm包源码AMD安装require.js安装示例ES6Module安装通过Vue.use()来全局安装示例./Home.vue

  3. AJAX POST数据中文乱码解决

    前端使用encodeURI进行编码后台java.net.URLDecoder进行解码编解码工具

  4. Koa2框架利用CORS完成跨域ajax请求

    实现跨域ajax请求的方式有很多,其中一个是利用CORS,而这个方法关键是在服务器端进行配置。本文仅对能够完成正常跨域ajax响应的,最基本的配置进行说明。这样OPTIONS请求就能够通过了。至此为止,相当于仅仅完成了预检,还没发送真正的请求呢。

  5. form提交时,ajax上传文件并更新到&lt;input&gt;中的value字段

  6. ajax的cache作用

    filePath="+escape;},error:{alert;}});解决方案:1.加cache:false2.url加随机数正常代码:网上高人解读:cache的作用就是第一次请求完毕之后,如果再次去请求,可以直接从缓存里面读取而不是再到服务器端读取。

  7. 浅谈ajax上传文件属性contentType = false

    默认值为contentType="application/x-www-form-urlencoded".在默认情况下,内容编码类型满足大多数情况。在这里,我们主要谈谈contentType=false.在使用ajax上传文件时:在其中先封装了一个formData对象,然后使用post方法将文件传给服务器。说到这,我们发现在JQueryajax()方法中我们使contentType=false,这不是冲突了吗?这就是因为当我们在form标签中设置了enctype=“multipart/form-data”,

  8. 909422229_ajaxFileUpload上传文件

    ajaxFileUpload.js很多同名的,因为做出来一个很容易。我上github搜AjaxFileUpload出来很多类似js。ajaxFileUpload是一个异步上传文件的jQuery插件传一个不知道什么版本的上来,以后不用到处找了。语法:$.ajaxFileUploadoptions参数说明:1、url上传处理程序地址。2,fileElementId需要上传的文件域的ID,即的ID。3,secureuri是否启用安全提交,默认为false。4,dataType服务器返回的数据类型。6,error

  9. AJAX-Cache:一款好用的Ajax缓存插件

    原文链接AJAX-Cache是什么Ajax是前端开发必不可少的数据获取手段,在频繁的异步请求业务中,我们往往需要利用“缓存”提升界面响应速度,减少网络资源占用。AJAX-Cache是一款jQuery缓存插件,可以为$.ajax()方法扩展缓存功能。

  10. jsf – Ajax update/render在已渲染属性的组件上不起作用

    我试图ajax更新一个有条件渲染的组件。我可以确保#{user}实际上是可用的。这是怎么引起的,我该如何解决呢?必须始终在ajax可以重新呈现之前呈现组件。Ajax正在使用JavaScriptdocument.getElementById()来查找需要更新的组件。但是如果JSF没有将组件放在第一位,那么JavaScript找不到要更新的内容。解决方案是简单地引用总是渲染的父组件。

返回
顶部