ssm+maven项目中配置webSocket

来源:https://blog.csdn.net/chenyidong521/article/details/52695093

只说明要在ssm的Maven项目中添加WebSocket的方法,使用SocketJs框架进行搭建

首先在搭建完成的ssm的Maven项目的pom文件中添加如下节点

 <properties>
    <spring.version>4.3.3.RELEASE</spring.version>
    <jackson.version>2.8.3</jackson.version>
  </properties>
    <!-- socketJs start -->
  <dependencies>
    <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>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-websocket</artifactId>
           <version>${spring.version}</version>
        </dependency>
        <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-messaging</artifactId>
           <version>${spring.version}</version>
        </dependency>
        <!-- socketJs end -->


        <!-- spring start -->
        <dependency>
          <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>
        <!-- spring end -->
  </dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

web.xml中就是正常的ssm配置方法了

上面的内容包括了我们使用的jar包包括socketJs的jar包 
因为使用socket的话session在别的地方接受不到数据,所以设置一个拦截器来管理session.创建一个握手类


/**
 * websocket握手类
 * @author cheny
 *
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{

      @Override
      public boolean beforeHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,
          Map<String, Object> attributes) throws Exception {
        System.out.println("开始拦截类");
        return super.beforeHandshake(request, response, wsHandler, attributes);
      }

      @Override
      public void afterHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,
          Exception ex) {
        System.out.println("结束拦截类");
        super.afterHandshake(request, response, wsHandler, ex);
      }

    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

创建一个处理信息的类


/**
 * websocket工具类
 * @author cheny
 *
 */
public class WebsocketEndPoint extends TextWebSocketHandler {

      @Override
      protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        System.out.println("进入了工具类");
        TextMessage returnMessage = new TextMessage(message.getPayload()+" 后台的消息");
        session.sendMessage(returnMessage);
      }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

然后再Springmvc.xml文件中添加

   <mvc:annotation-driven/> 
   <mvc:default-servlet-handler /> 
     <mvc:resources location="/" mapping="/**"/> 

    <bean id="myHandler" class="com.turing.websocket.WebsocketEndPoint"></bean>
    <websocket:handlers allowed-origins="*">
        <websocket:mapping path="/myHandler" handler="myHandler"/>
        <websocket:handshake-interceptors>
            <bean class="com.turing.websocket.HandshakeInterceptor"/>
        </websocket:handshake-interceptors>
    </websocket:handlers>

    <websocket:handlers allowed-origins="*">
        <websocket:mapping path="/sockjs/myHandler" handler="myHandler"/>
        <websocket:sockjs/>
    </websocket:handlers>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在jsp中的内容

<body>

<div>
  <div id="connect-container">
    <input id="radio1" type="radio" name="group1" onclick="updateUrl('/socket/myHandler');">
      <label for="radio1">W3C WebSocket</label>
    <br>
    <input id="radio2" type="radio" name="group1" onclick="updateUrl('/socket/sockjs/myHandler');">
      <label for="radio2">SockJS</label>
    <div>
      <button id="connect" onclick="connect();">链接</button>
      <button id="disconnect" disabled="disabled" onclick="disconnect();">断开</button>
    </div>
    <div>
      <textarea id="message" style="width: 350px" placeholder="输入要发送的消息"></textarea>
    </div>
    <div>
      <button id="echo" onclick="echo();" disabled="disabled">发送消息</button>
    </div>
  </div>
  <div id="console-container">
    <div id="console"></div>
  </div>
</div>
</body>

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

    //修改url,提供了两种url一种是wbsocket的一种是sockjs的
    function updateUrl(urlPath) {
        //如果链接中有sockjs字段就让链接等于传进来的本身
      if (urlPath.indexOf('sockjs') != -1) {
        url = urlPath;
      }
      else {
        if (window.location.protocol == 'http:') {
          url = 'ws://' + window.location.host + urlPath;
        } else {
          url = 'wss://' + window.location.host + urlPath;
        }
      }
    }


    //链接握手
      function connect() {
      if (!url) {
        alert('选择一个url');
        return;
      }
        //判断链接中是否有sockjs,如果有使用sockjs的方式拼链接,如果没有发送ws链接
      ws = (url.indexOf('sockjs') != -1) ? 
      //new SockJS(url, _reserved, options);默认三个参数,中间的基本不用,最后一个是sockjs提供的传输功能,参数是数组(默认是全部开启)
       new SockJS(url) : new WebSocket(url);
       //打开链接
      ws.onopen = function () {
        setConnected(true);
        log('消息: 链接已打开');
      };
      //获取消息
      ws.onmessage = function (event) {
      //调用下面的现实信息的方法
        log('推送的消息: ' + event.data);
      };
      //关闭链接
      ws.onclose = function (event) {
        setConnected(false);
         //调用下面的现实信息的方法
        log('消息: 链接已关闭');
        log(event);
      };
    }

    //发送消息
    function echo() {
      if (ws != null) {
      //获取到输入框中的消息
        var message = document.getElementById('message').value;
         //调用下面的现实信息的方法
        log('发送: ' + message);
        ws.send(message);
      } else {
        alert('消息没有链接地址,请重新连接');
      }
    }

    //将传输回来的信息显示在右侧
    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);
      //防止消息过长干div外面去
      while (console.childNodes.length > 25) {
        console.removeChild(console.firstChild);
      }
      //console.scrollTop = console.scrollHeight;
    }


    //关闭链接的时候将ws链接清空
    function disconnect() {
      if (ws != null) {
        ws.close();
        ws = null;
      }
      setConnected(false);
    }
  </script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120

最后注意在web.xml中的spring的默认过滤器DispatcherServlet中的url-pattern

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:/spring_mvc.xml</param-value>  
    </init-param>  

  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

猜你喜欢

转载自blog.csdn.net/rentian1/article/details/80758950