javabean方式配置(推荐) package com.ahutshop.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(WebSocketPushHandler(), "/webSocketServer.action").addInterceptors(new MyWebSocketInterceptor()).setAllowedOrigins("*"); registry.addHandler(WebSocketPushHandler(), "/sockjs/webSocketServer.action") .addInterceptors(new MyWebSocketInterceptor()).withSockJS(); } @Bean public WebSocketHandler WebSocketPushHandler() { return new WebSocketPushHandler(); } } spring.xml中配置扫描包 <!-- 扫描包 --> <context:component-scan base-package="com.ahutshop.websocket" />
注意:
1. /webSocketServer.action之所以要加上.action的后缀,是因为web.xmlk中配置了拦截的后缀名为.action
<!-- springmvc模块 --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <!-- 支持异步 --> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping>
2 .setAllowedOrigins(“*”)中的*代表合法的请求域名,该方法接受一个可变数组作为参数,一定要配置,不然会请求时会出现403
xml方式配置(省略)
微信小程序
1.websocket.wxml
<!--pages/websocket/websocket.wxml--> <view> <view> </view> <view> <button bindtap="connectWebsocket" type="primary">连接websocket</button> </view> </view>
2.websocket.js
// pages/websocket/websocket.js Page({ /** * 页面的初始数据 */ data: { }, connectWebsocket: function () { wx.connectSocket({ url: 'ws://localhost:8080/AhutShop/webSocketServer.action', data: { }, header: { 'content-type': 'application/json' }, method: "GET" }) wx.onSocketOpen(function (res) { console.log('WebSocket连接已打开!') }) wx.onSocketError(function (res) { console.log('WebSocket连接打开失败,请检查!') }) wx.onSocketMessage(function (res) { console.log('收到服务器内容:' + res.data) }) } })
运行效果
以上就是微信小程序 后台的建立,如有疑问请留言或者到本站社区交流讨论,本站关于微信小程序的文章还有很多,希望大家多多搜索查阅,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
您可能感兴趣的文章: