开发环境(最低版本):spring 4.0+java7+tomcat7.0.47+sockjs

前端页面要引入:

<script src="http://cdn.jsdelivr.net/sockjs/1/sockjs.min.js"></script>

maven依赖:

<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>

前端js:

var ws = null;
function openWebSocket(){
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
ws = new WebSocket("ws://"+window.location.host+"/项目名称/visualizationWebSocket.do?type=mall");
} else {
ws = new SockJS("http://"+window.location.host+"/项目名称/sockjs/visualizationWebSocket/info?type=mall");
}
ws.onopen = function () { };
  //这个事件是接受后端传过来的数据
ws.onmessage = function (event) {
//根据业务逻辑解析数据
};
ws.onclose = function (event) { };
}

我实现连接后台的方式如下:

//页面已加载后加载后台数据
$(function (){
$.ajax({
cache:false,
data:"",
type:"post",
url:"",
success:function(data, textStatus){
if(data && data.status === "1"){
 //这里可以初始化操作
openWebSocket();//websocket连接到后台
if(ws){
setTimeout(function (){
ws.send("");//发送信息到后台,开始有数据跟新就写到前端显示
},3000);
}
} else {
alert("操作失败!");
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){}
});
function zeroPadding(num, digit) {
var zero = '';
for(var i = 0; i < digit; i++) {
zero += '0';
}
return (zero + num).slice(-digit);
}
function showDate() {
var date = new Date();
var str = "" + zeroPadding(date.getFullYear(),4) + "-";
str += zeroPadding((date.getMonth() + 1),2) + "-";
str += zeroPadding(date.getDate(),2) + "&nbsp;&nbsp;&nbsp;&nbsp;";
str += zeroPadding(date.getHours(),2) + ':';
str += zeroPadding(date.getMinutes(),2) + ':';
str += zeroPadding(date.getSeconds(),2) + '';
return str;
} setInterval(function () {
$('.data-time').html(showDate)
}, 1000); });

后端:

webSocket配置

package com.snw.supplyChain.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration
@EnableWebSocket
@EnableWebMvc
public class VisualizationWebSocketConfig implements WebSocketConfigurer { public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
     //这里的url要与页面的url一致
webSocketHandlerRegistry.addHandler(myHandler(),"/visualizationWebSocket.do").addInterceptors(new VisualizationHandshakeInterceptor());
     //至于这里为什么要加info,我遇见的情况是,当我使用sockjs来代替websocket时,连接的后面会自动加上info
webSocketHandlerRegistry.addHandler(myHandler(),"/sockjs/visualizationWebSocket/info").addInterceptors(new VisualizationHandshakeInterceptor()).withSockJS();
}
@Bean
public WebSocketHandler myHandler(){
return new VisualizationWebSocketHandler();
} }

回话拦截器

package com.snw.supplyChain.websocket;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; import javax.servlet.http.HttpServletRequest;
import java.util.Map;
//回话拦截器
public class VisualizationHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
     //获取请求参数,首先我们要获取HttpServletRequest对象才能获取请求参数;当ServerHttpRequset的层次结构打开后其子类可以获取到我们想要的http对象,那么就简单了。
    //我这里是把获取的请求数据绑定到session的map对象中(attributes)
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
String id = servletRequest.getSession().getId();
System.out.println("beforeHandshake: \n"+id);
String type = servletRequest.getParameter("type");
attributes.put("mall",type);
return super.beforeHandshake(request, response, wsHandler, attributes);
} @Override
public void afterHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Exception ex) {
System.out.println("After Handshake");
super.afterHandshake(request, response, wsHandler, ex);
}
}

websocket处理器

处理器里面可以注入想要的service

package com.snw.supplyChain.websocket;

import com.snw.supplyChain.model.VisualizationProduct;
import com.snw.supplyChain.service.IVisualizationService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler; import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; public class VisualizationWebSocketHandler extends TextWebSocketHandler {
private static final Map<String,WebSocketSession> sessions = new HashMap<String, WebSocketSession>();
private static final Map<String,Thread> threads = new HashMap<String, Thread>();
private Thread polingVisualization = null;
//用户标识
private static final String CLIENT_ID = "sessionId";
@Autowired
private IVisualizationService visualizationService; @Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("afterConnectionEstablished: \n"+session.getId());
Object sessionType = session.getAttributes().get("mall");
if(sessionType != null && "mall".equals(sessionType)){
sessions.put(CLIENT_ID,session);
sessions.put(session.getId(),session);
}
super.afterConnectionEstablished(session);
} @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
Thread thread = threads.get(session.getId());
if(thread != null){
thread.interrupt();
try {
thread.join();
threads.remove(session.getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sessions.remove(session.getId());
sessions.remove(CLIENT_ID);
polingVisualization = null;
try {
super.afterConnectionClosed(session, status);
} catch (Exception e) {
}
}
   //这里是处理前端发送的消息以及返回给前端的数据
    //可以从session里面获取attributes,
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
super.handleTextMessage(session, message);
Thread thread = threads.get(session.getId());
if(thread == null){
System.out.println("handleTextMessage: \n"+session.getId());
WebSocketSession sessi = sessions.get(session.getId());
if(sessi == null){
sessions.put(session.getId(),session);
} else {
session = sessi;
}
final WebSocketSession localSession = session;
final TextMessage localMessage = message;
String payload = message.getPayload();
if(StringUtils.isNotBlank(payload)){
String[] split = payload.split("_");
if(StringUtils.isNotBlank(split[2])){
if("mall".equals(split[1])){
final int universalid = Integer.parseInt(split[2]);
               //这里的Thread可以用java.util.concurrent代替
Thread polingVisualization = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
polingVisualization(localSession, localMessage, universalid);
try {
Thread.sleep(180000);//
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
polingVisualization.start();
threads.put(sessi.getId(),polingVisualization);
}
}
}
}
} private VisualizationProduct polingVisualization(WebSocketSession session,
TextMessage message,Integer universalid) throws IOException {
VisualizationProduct visualizationProduct = visualizationService.findInquiryPriceOrderVisualization(universalid);
Map<String,Object> dataMap = new HashMap<String, Object>();
dataMap.put("status","1");
dataMap.put("visualizationProduct", visualizationProduct);
String dataStr = JSONObject.fromObject(dataMap).toString();
TextMessage returnMessage = new TextMessage(dataStr);
session.sendMessage(returnMessage);
return visualizationProduct;
} /**
* 给正在发布的商品发送新数据
* @param universalid 发布会ID
* @param sessionId
*/
public void sendNewProductDatas(Integer universalid, String sessionId){
if(universalid != null){
Set<String> keys = sessions.keySet();
for (String key : keys) {
WebSocketSession webSocketSession = sessions.get(key);
if(webSocketSession != null && webSocketSession.isOpen()){
VisualizationProduct visualizationProduct = visualizationService.findInquiryPriceOrderVisualization(universalid);
Map<String,Object> dataMap = new HashMap<String, Object>();
dataMap.put("status","1");
dataMap.put("visualizationProduct", visualizationProduct);
String dataStr = JSONObject.fromObject(dataMap).toString();
System.out.println(dataStr);
TextMessage returnMessage = new TextMessage(dataStr);
try {
webSocketSession.sendMessage(returnMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}

spring配置文件

文件标签,根据需要的添加,比如:websocket的xmlns和xsi:schemaLocation

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.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
http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">
<!-- 配置好处理器 -->
<bean id="websocketHandler" class="com.snw.supplyChain.websocket.VisualizationWebSocketHandler"/>
<!-- 配置拦截器 -->
<websocket:handlers>
<websocket:mapping path="/visualizationWebSocket.do" handler="websocketHandler"/><!-- 连接的URL -->
<websocket:handshake-interceptors>
<bean class="com.snw.supplyChain.websocket.VisualizationHandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>

欢迎各位大神指点其中不足哟。

逻辑处理

springMVC(spring)+WebSocket案例(获取请求参数)的更多相关文章

  1. Spring 中Controller 获取请求参数的方法笔记

    1.直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交.若"Content-Type"="application/ ...

  2. spring(spring mvc)整合WebSocket案例(获取请求参数)

    开发环境(最低版本):spring 4.0+java7+tomcat7.0.47+sockjs 前端页面要引入: <script src="http://cdn.jsdelivr.ne ...

  3. 学习SpringMVC——如何获取请求参数

    @RequestParam,你一定见过:@PathVariable,你肯定也知道:@QueryParam,你怎么会不晓得?!还有你熟悉的他(@CookieValue)!她(@ModelAndView) ...

  4. springMvc源码学习之:spirngMVC获取请求参数的方法2

    @RequestParam,你一定见过:@PathVariable,你肯定也知道:@QueryParam,你怎么会不晓得?!还有你熟悉的他 (@CookieValue)!她(@ModelAndView ...

  5. Spring MVC如何获取请求中的参数

    目录 一.获取URL中路径参数 1.1 @PathVariable 注解 1.2 @PathParam 注解 二.获取请求参数: 2.1 GET请求 2.1.1 获取请求中的单个参数:@Request ...

  6. SpringMVC 获取请求参数

    1.获取Request response对象 在SpringMVC的注解开发中,可以选择性的接收Request和Response对象来使用 2.获取request对象请求参数 a.通过request对 ...

  7. 【SpringMVC】获取请求参数

    通过ServletAPI获取 test.html <a th:href="@{/testServletAPI(username='admin',password=123456)}&qu ...

  8. 学习SpirngMVC之如何获取请求参数

    学习SpringMVC——如何获取请求参数   @RequestParam,你一定见过:@PathVariable,你肯定也知道:@QueryParam,你怎么会不晓得?!还有你熟悉的他(@Cooki ...

  9. request对象常用API 获取请求参数的值 request应用 MVC设计模式

    1 request对象常用API   1)表示web浏览器向web服务端的请求   2)url表示访问web应用的完整路径:http://localhost:8080/day06/Demo1     ...

随机推荐

  1. How to SetUp The Receiving Transaction Manager

    In this Document   Goal   Solution   References APPLIES TO: Oracle Inventory Management - Version: 1 ...

  2. HDTV(1920x1080)码率和视频质量关系的研究 1 (前期准备)

    Hans Hoffmann等人在论文<Studies on the Bit Rate Requirements for a HDTV Format With 1920 x 1080 pixel ...

  3. 预装WIN8的电脑是GPT分区模式,无法安装WIN7

    本人的笔记本自带的是WIN8系统,现在想安装WIN7的系统,但是安装不了,提示"windows无法安装到这个磁盘.选中的磁盘采用GPT分区形式". 通过上网搜索得知WIN7一般安装 ...

  4. Gradle 1.12用户指南翻译——第二十九章. Checkstyle 插件

    其他章节的翻译请参见: http://blog.csdn.net/column/details/gradle-translation.html 翻译项目请关注Github上的地址: https://g ...

  5. 数据结构是哈希表(hashTable)

    哈希表也称为散列表,是根据关键字值(key value)而直接进行访问的数据结构.也就是说,它通过把关键字值映射到一个位置来访问记录,以加快查找的速度.这个映射函数称为哈希函数(也称为散列函数),映射 ...

  6. Android实现RecyclerView侧滑删除和长按拖拽-ItemTouchHelper

    RecyclerView这个被誉为ListView和GirdView的替代品,它的用法在之前的一篇博文中就已经讲过了,今天我们就来实现RecyclerView的侧滑删除和长按拖拽功能,实现这两个功能我 ...

  7. OpenCV混合高斯模型函数注释说明

    OpenCV混合高斯模型函数注释说明 一.cvaux.h #define CV_BGFG_MOG_MAX_NGAUSSIANS 500 //高斯背景检测算法的默认参数设置 #define CV_BGF ...

  8. 超精简易用cocoaPods的安装和使用

    cocoaPods 安装和使用 第一步:替换ruby源 $ gem sources -l                                查看当前ruby的源 $ gem sources ...

  9. Python Django开发中XSS内容过滤问题的解决

    from:http://stackoverflow.com/questions/699468/python-html-sanitizer-scrubber-filter 通过下面这个代码就可以把内容过 ...

  10. webstorm配置eslint【标记错误,修复错误】

    项目中经常用到eslint语法,结合个人经验,用webstorm配置eslint "文件"->"默认设置"->"语言&框架&quo ...