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

Front end page to be introduced :

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

maven rely on :

<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>

front end js:

var ws = null;
function openWebSocket(){
// Determine whether the current browser supports it WebSocket
if ('WebSocket' in window) {
ws = new WebSocket("ws://"+window.location.host+"/ Project name /visualizationWebSocket.do?type=mall");
} else {
ws = new SockJS("http://"+window.location.host+"/ 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 (){
$.ajax({
cache:false,
data:"",
type:"post",
url:"",
success:function(data, textStatus){
if(data && data.status === "1"){
// Here you can initialize the operation
openWebSocket();//websocket Connect to the background
if(ws){
setTimeout(function (){
ws.send("");// Send information to the background , When the data is updated, it is written to the front-end display
},3000);
}
} 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 () {
$('.data-time').html(showDate)
}, 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
@EnableWebSocket
@EnableWebMvc
public class VisualizationWebSocketConfig implements WebSocketConfigurer { public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
// there url To connect with the url Agreement
webSocketHandlerRegistry.addHandler(myHandler(),"/visualizationWebSocket.do").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();
}
@Bean
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 org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; import javax.servlet.http.HttpServletRequest;
import java.util.Map;
// Call back interceptor
public class VisualizationHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
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");
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 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 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;
// User ID
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) {
}
}
// 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,
@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]);
// there Thread It can be used java.util.concurrent Instead of
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;
} /**
* 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("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 The configuration file

Document labels , Add as needed , such as :websocket Of xmlns and 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">
<!-- Configure the processor -->
<bean id="websocketHandler" class="com.snw.supplyChain.websocket.VisualizationWebSocketHandler"/>
<!-- Configure interceptors -->
<websocket:handlers>
<websocket:mapping path="/visualizationWebSocket.do" handler="websocketHandler"/><!-- Connected URL -->
<websocket:handshake-interceptors>
<bean class="com.snw.supplyChain.websocket.VisualizationHandshakeInterceptor"/>
</websocket:handshake-interceptors>
</websocket:handlers>

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="http://cdn.jsdelivr.ne ...

  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 java.io.Serializable; 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 http://www.hollischuang.com/archives/489 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("https://www.baidu.com&qu ...

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

    Page Jump Page Jump url Must be added automatically at the end [\], So in urls.py 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 ...