最近接触了小程序的开发,后端选择Java,因为小程序的代码运行在腾讯的服务器上,而我们自己编写的Java代码运行在我们自己部署的服务器上,所以一开始不是很明白小程序如何与后台进行通信的,然后查找资料发现结合了官方提供的api后好像和我们普通的web前后端通信也没有多大的区别,有想法后就写了这个测试程序。
大家在刚开始开发的时候一般都没有自己的服务器及域名,所以大家在本地编写的时候,在“详细”下的“项目设置”里面将“不校验域名安全性”勾选。
可先阅读官方文档
OBJECT参数说明:
success返回参数说明:
data 数据说明:
最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
header['content-type']
为 application/json
的数据,会对数据进行 JSON 序列化header['content-type']
为 application/x-www-form-urlencoded
的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)必须加上{}
主要框架springboot,开发工具idea,服务器阿里云服务器。
<!-- spring boot 核心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot整合jsp -->
<!-- tomcat 的支持. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
server:
port: 8083
ssl:
key-store: classoath:xxxxxx.pfx
key-store-password: xxxxxx
key-store-type: xxxxxx
在实际项目中可能涉及数据库,还要整合mybatis,在文章中,仅仅做测试就不做使用数据库的测试
package com.wx.m3;
@ComponentScan(basePackages= "com.wx.m3")//添加扫包@ComponentScan(basePackages= "")
@EnableAutoConfiguration
public class M3Application {
public static void main(String\[\] args) {
SpringApplication.run(M3Application.class, args);
}
}
启动项目时直接右击run即可
@RestController
@SpringBootApplication
public class IndexController {
@RequestMapping("getUser")
public Map<String,Object> getUser(){
System.out.println("微信小程序正在调用...");
Map<String,Object> map = new HashMap<String, Object>();
List<String> list = new ArrayList<String>();
list.add("Amy");
list.add("Cathy");
map.put("list",list);
System.out.println("微信小程序调用完成...");
return map;
}
@RequestMapping("")
public String getTest(){
return "Hello world";
}
}
至此简易的后端框架基本完成
说明:@RestController与Controller注解的区别
@RestController相当于它能实现将后端得到的数据在前端页面(网页)中以json串的形式传递。
微信小程序与后台数据之间的数据传递就是以json报文的形式传递。这也是选择springboot框架开发小程序后台的主要原因之一,可以方便进行小程序后套开发
下面以一个简单的按钮请求数据为例:
Page({
data:{
list: ''
},
houduanButton1:function(){
var that = this;
wx.request({
url: 'http://localhost:8083/getUser',
method: 'GET',
header: {
'content-type':'application/json'
},
success: function(res){
console.log(res.data);
var list = res.data.list;
if(list == null) {
var toastText = '数据获取失败';
wx.showToast({
title: toastText,
icon: '',
duration: 2000
});
} else{
that.setData({
list: list
})
}
}
})
}
})
将hello放到第一行,则首先进入hello.wxml
测试结果如下所示:
点击按钮显示姓名
手机扫一扫
移动阅读更方便
你可能感兴趣的文章