Spring自从4.0开始提供了对websocket的支持,配合sockjs,可以部分兼容到IE6,websocket终于可以大行其道了。
实际使用中遇到不少问题,逐步列举出来,避免以后忘掉。
- 由于浏览器设置了http代理,结果创建websocket时失败,提示:Error in connection establishment: net::ERR_TUNNEL_CONNECTION_FAILED。取消浏览器代理后恢复正常。
- 在web.xml中,DispatcherServlet和spring-mvc需要用到的全部filter,都需要加上<async-supported>true</async-supported>,以便在sockjs兼容不支持websocket的浏览器时使用。
- 工程使用spring-mvc传统的方式配置,即使用ContextLoaderListener来加载root的Spring-contextConfigLocation(除Controller外的其他Component),使用DispatcherServlet来加载Controller。而处理websocket的业务逻辑写在Controller中,加上了@MessageMapping的注解,结果请求根本到不了Controller里面去。后来发现AbstractMethodMessageHandler负责扫描@MessageMapping,但是在该类的子类实例化时,把Spring的Root Context扔进去了,这里面是没有Controller的类的,所以后面websocket的请求就到不了Controller。将websocket的相关配置文件放到DispatcherServlet里去加载,于是问题解决。
- GitHub上下的websocket例子有的用Spring3.2以后的零配置,在整到自己项目过程中 出现两个上下文加载
相关配置示例:
web.xml:
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath*:/applicationContext*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <servlet>
- <servlet-name>SpringMVC</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath*:/spring-*.xml
- </param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- <async-supported>true</async-supported>
- </servlet>
applicationContext.xml:
- <context:component-scan base-package="xxx.xxx">
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
spring-mvc.xml:
- <context:component-scan base-package="x.x.x" use-default-filters="false">
- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
- </context:component-scan>
spring-websocket.xml:
- <websocket:message-broker application-destination-prefix="/app">
- <websocket:stomp-endpoint path="/chat">
- <websocket:sockjs/>
- </websocket:stomp-endpoint>
- <websocket:simple-broker prefix="/public,/private"/>
- </websocket:message-broker>