spring springmvc js websocket 监听

第一步:web.xml中支持异步。所有的filter及servlet

<filter>
    <filter-name>characterEncoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <async-supported>true</async-supported>
  </filter>
  
  <filter-mapping>
    <filter-name>characterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 注册中央调度器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name><!-- 随便 -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 指定springmvc配置文件位置及文件名 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext-mvc.xml</param-value><!-- springmvc的配置文件,classpath代表类路径下 -->
    </init-param>
    <!-- 写一个>0的数字,越小优先级越高(<=0和没有设置没区别),表明tomcat服务器在启动的时候,就将DispatcherServlet对象给创建了 -->
    <!-- 在tomcat启动时,直接创建当前servlet -->
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>

第二步。pom.xml依赖

<!-- for support web socket -->  
        <dependency>  
            <groupId>javax.websocket</groupId>  
            <artifactId>javax.websocket-api</artifactId>  
            <version>1.1</version>  
            <scope>provided</scope> <!-- 注意,scope必须为provided,否则runtime会冲突,如果使用tomcat 8,还需要将TOMCAT_HOME/lib下的javax.websocket-api.jar一并删除 -->  
        </dependency> 
        
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.3.3</version>
        </dependency>

第三步:

package com.ldr.websocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
/**
 * 
 * @author Wang&Yang
 * @email 867986155@qq.com
 * @date 2018-05-02
 * @remark esno company
 * @version 1.0.0
 * @description:
 * 这个类表示启用websocket消息处理,以及收发消息的域

    config.enableSimpleBroker("/queue", "/topic");这句表示在/queue", "/topic这两个域上可以向客户端发消息;

    registry.addEndpoint("/endpointChat").withSockJS();客户端在此连接websocket server
 */
@Configuration /*别忘记了要让spring管理咯*/ 
@EnableWebSocketMessageBroker  
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {  
  
    @Override  
    public void configureMessageBroker(MessageBrokerRegistry config) {  
        config.enableSimpleBroker("/queue", "/topic");
    }  
  
    @Override  
    public void registerStompEndpoints(StompEndpointRegistry registry) {  
        //注册一个名字为"endpointChat" 的endpoint,并指定 SockJS协议。   点对点-用
        registry.addEndpoint("/endpointChat").withSockJS();  
    }  
  
}  
package com.ldr.websocket;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ldr.base.GsonBean;

@Controller  
public class WebSocketController {  
  
    public SimpMessagingTemplate template;  
  
    @Autowired  
    public WebSocketController(SimpMessagingTemplate template) {  
        this.template = template;  
    }  
 
    
    @RequestMapping("/noticeDataGenResult")
    public void noticeDataGenResult(@RequestParam(value="fn") String fileName,@RequestParam(value="rc") String genResult/*1为成功,0为失败*/) {
            Map<String,String> datas=new HashMap<String,String>(5);
            datas.put("fileName", fileName);
            datas.put("genResult", genResult);
            template.convertAndSend("/topic/getResponse", new GsonBean(200, datas));
        }
    }

 

第四步:jsp

    <!-- websock.js -->
    <script type="text/javascript" src="../sys/js/websock/sockjs.min.js"></script>
    <script type="text/javascript" src="../sys/js/websock/stomp.min.js"></script>

$(function () {
        connect();
    });

    function connect() {
        var sock = new SockJS("../endpointChat");
        var stomp = Stomp.over(sock);
        stomp.connect('guest', 'guest', function(frame) {
            stomp.subscribe('/topic/getResponse', function (response) { //订阅/topic/getResponse 目标发送的消息。这个是在控制器的@SendTo中定义的。
                var resultObj=$.parseJSON(response.body);
                console.dir(resultObj);
            });
        });
        
    }

 

posted @ 2018-05-02 15:36  傻瓜不傻108  阅读(448)  评论(0编辑  收藏  举报