Spring4.0使用websocke遇到的一些问题

Spring自从4.0开始提供了对websocket的支持,配合sockjs,可以部分兼容到IE6,websocket终于可以大行其道了。

    实际使用中遇到不少问题,逐步列举出来,避免以后忘掉。

 

  1. 由于浏览器设置了http代理,结果创建websocket时失败,提示:Error in connection establishment: net::ERR_TUNNEL_CONNECTION_FAILED。取消浏览器代理后恢复正常。
  2. 在web.xml中,DispatcherServlet和spring-mvc需要用到的全部filter,都需要加上<async-supported>true</async-supported>,以便在sockjs兼容不支持websocket的浏览器时使用。
  3. 工程使用spring-mvc传统的方式配置,即使用ContextLoaderListener来加载root的Spring-contextConfigLocation(除Controller外的其他Component),使用DispatcherServlet来加载Controller。而处理websocket的业务逻辑写在Controller中,加上了@MessageMapping的注解,结果请求根本到不了Controller里面去。后来发现AbstractMethodMessageHandler负责扫描@MessageMapping,但是在该类的子类实例化时,把Spring的Root Context扔进去了,这里面是没有Controller的类的,所以后面websocket的请求就到不了Controller。将websocket的相关配置文件放到DispatcherServlet里去加载,于是问题解决。
  4. GitHub上下的websocket例子有的用Spring3.2以后的零配置,在整到自己项目过程中 出现两个上下文加载

相关配置示例:

web.xml:

Xml代码   收藏代码
  1. <context-param>  
  2.         <param-name>contextConfigLocation</param-name>  
  3.         <param-value>classpath*:/applicationContext*.xml</param-value>  
  4.     </context-param>  
  5.   
  6. <listener>  
  7.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  8.     </listener>  
  9.   
  10. <servlet>  
  11.         <servlet-name>SpringMVC</servlet-name>  
  12.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  13.         <init-param>  
  14.             <param-name>contextConfigLocation</param-name>  
  15.             <param-value>  
  16.                 classpath*:/spring-*.xml  
  17.             </param-value>  
  18.         </init-param>  
  19.         <load-on-startup>1</load-on-startup>  
  20.         <async-supported>true</async-supported>  
  21.     </servlet>  

 applicationContext.xml:

Xml代码   收藏代码
  1. <context:component-scan base-package="xxx.xxx">  
  2.         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  3.     </context:component-scan>  

 spring-mvc.xml:

Xml代码   收藏代码
  1. <context:component-scan base-package="x.x.x" use-default-filters="false">  
  2.         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
  3.     </context:component-scan>  

 spring-websocket.xml:

Xml代码   收藏代码
  1. <websocket:message-broker application-destination-prefix="/app">  
  2.         <websocket:stomp-endpoint path="/chat">  
  3.             <websocket:sockjs/>  
  4.         </websocket:stomp-endpoint>  
  5.         <websocket:simple-broker prefix="/public,/private"/>  
  6.     </websocket:message-broker>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值