ssm+maven项目中配置webSocket

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

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

 <properties>
    <spring.version>4.3.3.RELEASEspring.version>
    <jackson.version>2.8.3jackson.version>
  properties>
    
  <dependencies>
    <dependency>
          <groupId>javax.servletgroupId>
          <artifactId>javax.servlet-apiartifactId>
          <version>3.1.0version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-coreartifactId>
            <version>${jackson.version}version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>${jackson.version}version>
        dependency>

        <dependency>
           <groupId>org.springframeworkgroupId>
           <artifactId>spring-websocketartifactId>
           <version>${spring.version}version>
        dependency>
        <dependency>
           <groupId>org.springframeworkgroupId>
           <artifactId>spring-messagingartifactId>
           <version>${spring.version}version>
        dependency>
        


        
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-coreartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webmvcartifactId>
          <version>${spring.version}version>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-context-supportartifactId>
          <version>${spring.version}version>
        dependency>
        
  dependencies>

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

    }

创建一个处理信息的类


/**
 * 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);
      }
}

然后再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>

在jsp中的内容

<body>

<div>
  <div id="connect-container">
    <input id="radio1" type="radio" name="group1" onclick="updateUrl('/socket/myHandler');">
      <label for="radio1">W3C WebSocketlabel>
    <br>
    <input id="radio2" type="radio" name="group1" onclick="updateUrl('/socket/sockjs/myHandler');">
      <label for="radio2">SockJSlabel>
    <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>

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

  <servlet>
    <servlet-name>actionservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath:/spring_mvc.xmlparam-value>  
    init-param>  

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

到此在spring框架中配置websocket方法结束

你可能感兴趣的:(ssm)