spring+websocket整合(springMVC+spring+MyBatis即SSM框架和websocket技术的整合)
java-websocket的搭建非常之容易,没用框架的童鞋可以在这里下载撸主亲自调教好的java-websocket程序:
spring4.0以后加入了对websocket技术的支持,在SSM(springMVC+spring+MyBatis)框架中集成websocket技术的曲折蛋疼直至成功喜悦之路。
- 1 在maven的pom.xml中加入websocket所依赖的jar包,什么,你不知道maven,快去度之或者查看撸主关于maven的博文恶补一下,spring-websocket所依赖的jar包有以下几个:
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <version>3.1.0</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.3.0</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.3.0</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-websocket</artifactId>
- <version>4.0.1.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-messaging</artifactId>
- <version>4.0.1.RELEASE</version>
- </dependency>
- 2 更新web.xml中namespace.xsd的版本,
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:websocket="http://www.springframework.org/schema/websocket"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd">
- 3 更新spring框架的jar包至4.0以上(spring-core, spring-context, spring-web and spring-webmvc)
- <dependency>
- <span style="white-space:pre"> </span><groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>${spring.version}</version>
- </dependency>
- 4 4.1创建websocket处理类
- package com.up.websocket.handler;
- import org.springframework.web.socket.TextMessage;
- import org.springframework.web.socket.WebSocketSession;
- import org.springframework.web.socket.handler.TextWebSocketHandler;
- public class WebsocketEndPoint extends TextWebSocketHandler {
- @Override
- protected void handleTextMessage(WebSocketSession session,
- TextMessage message) throws Exception {
- super.handleTextMessage(session, message);
- TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server");
- session.sendMessage(returnMessage);
- }
- }
- 4.2创建握手(handshake)接口
- package com.up.websocket;
- import java.util.Map;
- import org.springframework.http.server.ServerHttpRequest;
- import org.springframework.http.server.ServerHttpResponse;
- import org.springframework.web.socket.WebSocketHandler;
- import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
- public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{
- @Override
- public boolean beforeHandshake(ServerHttpRequest request,
- ServerHttpResponse response, WebSocketHandler wsHandler,
- Map<String, Object> attributes) throws Exception {
- System.out.println("Before Handshake");
- 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);
- }
- }
- 5 处理类和握手协议的spring配置(applicationContext.xml文件)
- <bean id="websocket" class="com.up.websocket.handler.WebsocketEndPoint"/>
- <websocket:handlers>
- <websocket:mapping path="/websocket" handler="websocket"/>
- <websocket:handshake-interceptors>
- <bean class="com.up.websocket.HandshakeInterceptor"/>
- </websocket:handshake-interceptors>
- </websocket:handlers>
- 6 客户端页面
- <!DOCTYPE html>
- <html>
- <head>
- <title>WebSocket/SockJS Echo Sample (Adapted from Tomcat‘s echo sample)</title>
- <style type="text/css">
- #connect-container {
- float: left;
- width: 400px
- }
- #connect-container div {
- padding: 5px;
- }
- #console-container {
- float: left;
- margin-left: 15px;
- width: 400px;
- }
- #console {
- border: 1px solid #CCCCCC;
- border-right-color: #999999;
- border-bottom-color: #999999;
- height: 170px;
- overflow-y: scroll;
- padding: 5px;
- width: 100%;
- }
- #console p {
- padding: 0;
- margin: 0;
- }
- </style>
- <script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
- <script type="text/javascript">
- var ws = null;
- var url = null;
- var transports = [];
- function setConnected(connected) {
- document.getElementById(‘connect‘).disabled = connected;
- document.getElementById(‘disconnect‘).disabled = !connected;
- document.getElementById(‘echo‘).disabled = !connected;
- }
- function connect() {
- alert("url:"+url);
- if (!url) {
- alert(‘Select whether to use W3C WebSocket or SockJS‘);
- return;
- }
- ws = (url.indexOf(‘sockjs‘) != -1) ?
- new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url);
- ws.onopen = function () {
- setConnected(true);
- log(‘Info: connection opened.‘);
- };
- ws.onmessage = function (event) {
- log(‘Received: ‘ + event.data);
- };
- ws.onclose = function (event) {
- setConnected(false);
- log(‘Info: connection closed.‘);
- log(event);
- };
- }
- function disconnect() {
- if (ws != null) {
- ws.close();
- ws = null;
- }
- setConnected(false);
- }
- function echo() {
- if (ws != null) {
- var message = document.getElementById(‘message‘).value;
- log(‘Sent: ‘ + message);
- ws.send(message);
- } else {
- alert(‘connection not established, please connect.‘);
- }
- }
- function updateUrl(urlPath) {
- if (urlPath.indexOf(‘sockjs‘) != -1) {
- url = urlPath;
- document.getElementById(‘sockJsTransportSelect‘).style.visibility = ‘visible‘;
- }
- else {
- if (window.location.protocol == ‘http:‘) {
- url = ‘ws://‘ + window.location.host + urlPath;
- } else {
- url = ‘wss://‘ + window.location.host + urlPath;
- }
- document.getElementById(‘sockJsTransportSelect‘).style.visibility = ‘hidden‘;
- }
- }
- function updateTransport(transport) {
- alert(transport);
- transports = (transport == ‘all‘) ? [] : [transport];
- }
- function log(message) {
- var console = document.getElementById(‘console‘);
- var p = document.createElement(‘p‘);
- p.style.wordWrap = ‘break-word‘;
- p.appendChild(document.createTextNode(message));
- console.appendChild(p);
- while (console.childNodes.length > 25) {
- console.removeChild(console.firstChild);
- }
- console.scrollTop = console.scrollHeight;
- }
- </script>
- </head>
- <body>
- <noscript><h2 style="color: #ff0000">Seems your browser doesn‘t support Javascript! Websockets
- rely on Javascript being enabled. Please enable
- Javascript and reload this page!</h2></noscript>
- <div>
- <div id="connect-container">
- <input id="radio1" type="radio" name="group1" onclick="updateUrl(‘‘/spring-websocket-uptest/websocket‘);">
- <label for="radio1">W3C WebSocket</label>
- <br>
- <input id="radio2" type="radio" name="group1" onclick="updateUrl(‘/spring-websocket-uptest/websocket‘);">
- <label for="radio2">SockJS</label>
- <div id="sockJsTransportSelect" style="visibility:hidden;">
- <span>SockJS transport:</span>
- <select onchange="updateTransport(this.value)">
- <option value="all">all</option>
- <option value="websocket">websocket</option>
- <option value="xhr-polling">xhr-polling</option>
- <option value="jsonp-polling">jsonp-polling</option>
- <option value="xhr-streaming">xhr-streaming</option>
- <option value="iframe-eventsource">iframe-eventsource</option>
- <option value="iframe-htmlfile">iframe-htmlfile</option>
- </select>
- </div>
- <div>
- <button id="connect" onclick="connect();">Connect</button>
- <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
- </div>
- <div>
- <textarea id="message" style="width: 350px">Here is a message!</textarea>
- </div>
- <div>
- <button id="echo" onclick="echo();" disabled="disabled">Echo message</button>
- </div>
- </div>
- <div id="console-container">
- <div id="console"></div>
- </div>
- </div>
- </body>
- </html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。