development environment ( Minimum version ):spring 4.0+java7+tomcat7.0.47+sockjs

Front end page to be introduced :

<script src=""></script>

maven rely on :


front end js:

var ws = null;
function openWebSocket(){
// Determine whether the current browser supports it WebSocket
if ('WebSocket' in window) {
ws = new WebSocket("ws://""/ Project name /");
} else {
ws = new SockJS("http://""/ Project name /sockjs/visualizationWebSocket/info?type=mall");
ws.onopen = function () { };
// This event is to accept the data from the back end
ws.onmessage = function (event) {
// Analyze data according to business logic
ws.onclose = function (event) { };

My way to connect to the background is as follows :

// Loading background data after page has been loaded 
$(function (){
success:function(data, textStatus){
if(data && data.status === "1"){
// Here you can initialize the operation
openWebSocket();//websocket Connect to the background
setTimeout(function (){
ws.send("");// Send information to the background , When the data is updated, it is written to the front-end display
} else {
alert(" operation failed !");
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 () {
}, 1000); });

Back end :

webSocket To configure

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
public class VisualizationWebSocketConfig implements WebSocketConfigurer { public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
// there url To connect with the url Agreement
webSocketHandlerRegistry.addHandler(myHandler(),"/").addInterceptors(new VisualizationHandshakeInterceptor());
// As for why we need to add info, What happened to me was , When I use sockjs Instead of websocket when , The connection is automatically followed by info
webSocketHandlerRegistry.addHandler(myHandler(),"/sockjs/visualizationWebSocket/info").addInterceptors(new VisualizationHandshakeInterceptor()).withSockJS();
public WebSocketHandler myHandler(){
return new VisualizationWebSocketHandler();
} }

Call back interceptor

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; import javax.servlet.http.HttpServletRequest;
import java.util.Map;
// Call back interceptor
public class VisualizationHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
public boolean beforeHandshake(ServerHttpRequest request,
ServerHttpResponse response, WebSocketHandler wsHandler,
Map<String, Object> attributes) throws Exception {
// Get request parameters , First of all, we need to get HttpServletRequest Object to get the request parameters ; When ServerHttpRequset After opening the hierarchy of, its subclasses can get what we want http object , So it's easy .
// Here I am binding the obtained request data to session Of map In the object (attributes)
HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
String id = servletRequest.getSession().getId();
System.out.println("beforeHandshake: \n"+id);
String type = servletRequest.getParameter("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 processor

The processor can inject what it wants 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;
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;
// User ID
private static final String CLIENT_ID = "sessionId";
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)){
} @Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
Thread thread = threads.get(session.getId());
if(thread != null){
try {
} catch (InterruptedException e) {
polingVisualization = null;
try {
super.afterConnectionClosed(session, status);
} catch (Exception e) {
// Here is to process the messages sent by the front end and the data returned to the front end
// It can be downloaded from session Get in there attributes,
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){
} else {
session = sessi;
final WebSocketSession localSession = session;
final TextMessage localMessage = message;
String payload = message.getPayload();
String[] split = payload.split("_");
final int universalid = Integer.parseInt(split[2]);
// there Thread It can be used java.util.concurrent Instead of
Thread polingVisualization = new Thread(new Runnable() {
public void run() {
try {
polingVisualization(localSession, localMessage, universalid);
try {
} catch (InterruptedException e) {
} catch (IOException e) {
} 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("visualizationProduct", visualizationProduct);
String dataStr = JSONObject.fromObject(dataMap).toString();
TextMessage returnMessage = new TextMessage(dataStr);
return visualizationProduct;
} /**
* Send new data to the product being released
* @param universalid Release conference 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("visualizationProduct", visualizationProduct);
String dataStr = JSONObject.fromObject(dataMap).toString();
TextMessage returnMessage = new TextMessage(dataStr);
try {
} catch (IOException e) {

spring The configuration file

Document labels , Add as needed , such as :websocket Of xmlns and xsi:schemaLocation

<beans xmlns=""
xmlns:xsi="" xmlns:p=""
xmlns:aop="" xmlns:mvc=""
<!-- Configure the processor -->
<bean id="websocketHandler" class="com.snw.supplyChain.websocket.VisualizationWebSocketHandler"/>
<!-- Configure interceptors -->
<websocket:mapping path="/" handler="websocketHandler"/><!-- Connected URL -->
<bean class="com.snw.supplyChain.websocket.VisualizationHandshakeInterceptor"/>

You are welcome to point out the shortcomings .

 Logical processing 

spring(spring mvc) Integrate WebSocket Case study ( Get request parameters ) More articles about

  1. springMVC(spring)+WebSocket Case study ( Get request parameters )

    development environment ( Minimum version ):spring 4.0+java7+tomcat7.0.47+sockjs Front end page to be introduced : <script src=" ...

  2. 【Java Web Developing learning 】Spring MVC Integrate WebSocket signal communication

    Spring MVC Integrate WebSocket signal communication Catalog ========================================================================= ...

  3. request Objects are commonly used API Gets the value of the request parameter request application MVC Design patterns

    1 request Objects are commonly used API   1) Express web Browser direction web Server side request   2)url To visit web Full path of application :http://localhost:8080/day06/Demo1     ...

  4. Study SpringMVC—— How to get request parameters

    @RequestParam, You must have seen :@PathVariable, You must know that :@QueryParam, How can you not know ?! And you know him (@CookieValue)! she (@ModelAndView) ...

  5. springMvc Source code learning :spirngMVC Method to get request parameters 2

    @RequestParam, You must have seen :@PathVariable, You must know that :@QueryParam, How can you not know ?! And you know him (@CookieValue)! she (@ModelAndView ...

  6. Study SpirngMVC How to get request parameters

    Study SpringMVC—— How to get request parameters   @RequestParam, You must have seen :@PathVariable, You must know that :@QueryParam, How can you not know ?! And you know him (@Cooki ...

  7. struts2 Three ways to get request parameters and pass them to JSP Method of parameters

    Follow up on the last article package test; import com.opensymphony.xwork2.ActionSupport; import javax.servlet.http.*; impo ...

  8. Structs2 The interceptor gets the request parameters

    Preface Environmental Science :window 10,JDK 1.7,Tomcat 7 Test code package com.szxy.interceptor; import java.util.Map; import jav ...

  9. ServletRequest HttpServletRequest Request method Get request parameters Request forwarding Request includes The difference between request forwarding and redirection Get the request header field

      ServletRequest  Basic concepts JavaWeb Medium "Request" object   For the actual    HttpServletRequest  perhaps   ServletRequest, ...

Random recommendation

  1. 【01-05】hibernate BaseDao

    BaseDao Interface definition package org.alohaworld.util.dao; import; import java.util.List; imp ...

  2. Xie Xinlun - OpenDev Original tutorial - Bluetooth device lookup class CxBthRadio &amp; CxBthRadioFind

    This is a concise Bluetooth device search class , Class name . The function name and variable name are named in Hungarian . Lowercase x It's my initials ( Xie Xinlun ), Personal habits , any similarity , Purely coincidental . CxBthRadioFind The use of : void CU ...

  3. Bluetooth Security Manager

    One . Concept     The Security Manager defines methods of pairing and key distribution, a protocol for those ...

  4. android Solutions to link Bluetooth instability

    My workaround I scan BLE for a short period of time 3-4 seconds then I turn scan OFF for 3-4 seconds ...

  5. 【 recommend 】Java It's worth reading how engineers become great gods from ordinary people

    This article comes from A little insight java As a programming language , In all kinds of programming languages, being a trendsetter always ranks in the top three , This fully affirms java Linguistic ...

  6. Selenium Eight basic positioning methods --- be based on python

    from selenium import  webdriver driver=webdriver.Firefox() driver.get(" ...

  7. Python The background and development Django( Session control )

    Page Jump Page Jump url Must be added automatically at the end [\], So in You need to add... In the routing table of [\] from django.shortcuts import redirect # Import retur ...

  8. Codeforces.954I.Yet Another String Matching Problem(FFT)

    Topic link \(Description\) For two strings \(a,b\), You can choose one character at a time , Change it into another character in both strings . Definition \(dis(a,b)\) In order to make \(a,b\) The minimum number of modifications required to equalize . ...

  9. Get to know UTF-16

    1) Let's talk about it UTF-16 It's a coding format . What is the encoding format ? It's how to store , That's how it's stored . What to store ? Save binary numbers . Why store binary numbers ? because Unicode In the character set, binary numbers and characters are mapped one by one , Save two ...

  10. 『TensorFlow Internals』 note _ Source structure

    zero . Data collection Know about columns :Bob Learn to walk Know and ask questions : How to study efficiently TensorFlow Code ?. Big brother Liu Guangcong (Github, Simple books ) Open source book :TensorFlow Internals, Strongly recommend ( This blog reference book ...