WEB.xml
</pre><pre name="code" class="html"> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring/ApplicationContext.xml</param-value> //这是spring核心配置文件的路径(自己修改自己对应的路径地址)
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener><span style="font-family: Arial, Helvetica, sans-serif;"> </span>
<servlet>
<servlet-name>dwr</servlet-name>
<servlet-class>org.directwebremoting.spring.DwrSpringServlet</servlet-class>
<!-- 指定DWR核心Servlet处于调试状态 -->
<init-param>
<param-name>debug</param-name>
<param-value>true</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>
</servlet>
<servlet-mapping>
<servlet-name>dwr</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
ApplicationContext.xml-----------(spring核心配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 启用注解 ,spring 的注解开启包-->
<context:annotation-config />
<context:component-scan base-package="com.tuozhen.web" />
<!-- 引入dwr bean配置文件 -->
<import resource="classpath*:config/dwr/dwr-context.xml" />------------------//这个才是关键的DWR核心配置路径
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
dwr-context.xml
<?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:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.directwebremoting.org/schema/spring-dwr
http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">
<bean id="chatService" class="com.tuozhen.web.v1.test.controller.ChatService">
<dwr:remote javascript="sm">
<dwr:include method="init" />
<dwr:include method="sendMessage" />
<dwr:include method="sendMessageToUser" />
</dwr:remote>
</bean>
</beans>
ChatService.class 这个也就是上门那个bean配置的
package com.tuozhen.web.v1.test.controller;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ScriptSessions;
import org.directwebremoting.WebContextFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.google.gson.Gson;
import com.tuozhen.web.common.annotate.ParamInit;
import com.tuozhen.web.v1.test.util.DwrScriptSessionManagerUtil;
public class ChatService {
@ParamInit
@RequestMapping("/login")
public void login(HttpServletRequest request,HttpServletResponse response) throws IOException{
Map<String,Object> data = (Map<String,Object>) request.getAttribute("data");
String userName = data.get("userName").toString();
System.out.println(userName);
request.getSession().setAttribute("userName", userName);
response.getWriter().print(new Gson().toJson(true));
}
public void init(final String userName){
System.out.println("初始化用户链接:"+userName);
ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
scriptSession.setAttribute(userName, userName);
DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();
try {
dwrScriptSessionManagerUtil.init();
} catch (ServletException e) {
e.printStackTrace();
}
}
public void sendMessageToUser(String toUserName , String message){
//开始推送
sendMessageAuto(toUserName,message);
}
/**
* 消息推送
* @param userid
* @param message
*/
public void sendMessageAuto(String toUserId, String message) {
final String userId = toUserId;
final String autoMessage = message;
Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
public boolean match(ScriptSession scriptSession) {
if (scriptSession.getAttribute(userId) == null)
return false;
else
return (scriptSession.getAttribute(userId).toString()).equals(userId);
}
}, 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);
}
}
});
}
}
DwrScriptSessionManagerUtil.class 监听scriptSession加入和销毁
package com.tuozhen.web.v1.test.util;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
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;
public class DwrScriptSessionManagerUtil extends DwrServlet{
private static final long serialVersionUID = 1L;
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 userName = session.getAttribute("userName").toString();
System.out.println("成功创建一个“"+userName+"”的Script会话");
ev.getSession().setAttribute(userName, userName);
}
public void sessionDestroyed(ScriptSessionEvent ev) {
System.out.println("销毁一个ScriptSession");
}
};
manager.addScriptSessionListener(listener);
}
}
好了 后台就OK了 现在 我们来看看 前台的。
1.登录页面,因为要登录了才能确定是谁发送的或者发送给谁,这样才能达到精准推送消息
login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" 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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=basePath%>js/jquery/jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function(){
$("#submit_login").click(function(){
var params = $("#login_form").serialize();
console.log(params);
$.ajax({
type: "post",
url: "v1/wh/chaService/login.tz",
data: params,
dataType: "json",
success: function(data){
console.log(data);
location.href = "test/dwr/chat.jsp"
}
});
});
});
</script>
</head>
<body>
<form id="login_form" action="">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="userPwd"/></td>
</tr>
<tr>
<td rowspan="2"><input id="submit_login" type="button" value="登录"/></td>
</tr>
</table>
</form>
</body>
</html>
2.发送消息与聊天页面
chat.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" 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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="<%=basePath%>js/jquery/jquery-1.10.1.js"></script>
<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/sm.js"></script>
<script type="text/javascript">
function init(){
var userName = '${userName}';
sm.init(userName);
}
function send(){
var toUserName = $("#toUserName").val();
var content = $("#content").val();
sm.sendMessageToUser(toUserName,content);
}
function showMessage(data){
<span style="white-space:pre"> </span>alert(data);
}
</script>
</head>
<body οnlοad="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);init();">
<textarea rows="20" cols="60" id="info" readonly="readonly"></textarea>
<hr/>
对方用户名:<input type="text" id="toUserName"/><br/>
消息:<textarea rows="5" cols="30" id="content"></textarea>
<input type="button" value=" Send " οnclick="send()" style="height: 85px; width: 85px;"/>
</body>
</html>