SSM项目集成websocket

本文介绍了如何在SSM(Spring、SpringMVC、MyBatis)项目中集成WebSocket,重点讲解了4个步骤:添加依赖、注解配置、拦截器配置以及消息处理器的设置。完成这些步骤后,后端的集成工作就完成了,接下来将配置前端的jsp页面。
摘要由CSDN通过智能技术生成

springmvc集成websocket需要4.0及以上版本
1.在项目的pom.xml中添加websocket所需jar

		<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.对websocket进行配置
springmvc对websocket配置分为两种,一是使用xml方法进行配置,二是使用注解方式配置,这里我们选择第二种方式进行配置

package com.ttf.ssm.base.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.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Configuration
@EnableWebMvc
@EnableWebSocket
public class SpringWebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    	/*
    	 * 添加拦截地址以及相应的websocket消息处理器
    	 */
        registry.addHandler(webSocketHandler(),"/websocket/socketServer.do").addInterceptors(new SpringWebSocketHandlerInterceptor());
        
        /*
         * 注册 sockJS,sockJs是spring对不能使用websocket协议的客户端提供一种模拟
         */
        registry.addHandler(webSocketHandler(), "/sockjs/socketServer.do").addInterceptors(new SpringWebSocketHandlerInterceptor()).withSockJS();
    }
 
    @Bean
    public TextWebSocketHandler webSocketHandler(){
        return new SpringWebSocketHandler();
    }
}

3.配置websocket服务的拦截器

package com.ttf.ssm.base.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRe
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值