微信小程序开发——后端Java(一)

一、前言

最近接触了小程序的开发,后端选择Java,因为小程序的代码运行在腾讯的服务器上,而我们自己编写的Java代码运行在我们自己部署的服务器上,所以一开始不是很明白小程序如何与后台进行通信的,然后查找资料发现结合了官方提供的api后好像和我们普通的web前后端通信也没有多大的区别,有想法后就写了这个测试程序。

二、微信小程序开发基础

1、不校验域名安全性

大家在刚开始开发的时候一般都没有自己的服务器及域名,所以大家在本地编写的时候,在“详细”下的“项目设置”里面将“不校验域名安全性”勾选。

 2、了解wx.request(OBJECT)

可先阅读官方文档

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)...)

3、.json文件不能为空

必须加上{}

三、Java后端编写

主要框架springboot,开发工具idea,服务器阿里云服务器。

1、创建一个maven项目,导入相关依赖: 

<!-- 统一版本控制 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<dependencies>
        <!-- freemarker渲染页面 -->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- 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>
</dependencies>

2、创建application.yml文件,修改一些配置参数等

server:
  port: 8083
  ssl:
    key-store: classoath:xxxxxx.pfx
    key-store-password: xxxxxx
    key-store-type: xxxxxx

在实际项目中可能涉及数据库,还要整合mybatis,在文章中,仅仅做测试就不做使用数据库的测试

3、首先修改springboot的启动程序:

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即可

 4、在写一个测试的controller进行微信小程序与java后端实现通信,controller代码如下:

@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框架开发小程序后台的主要原因之一,可以方便进行小程序后套开发

四、小程序发起网络请求

下面以一个简单的按钮请求数据为例:

hello.wxml文件:

<button bindtap='houduanButton1'>点击发起请求</button>
<view wx:for="{{list}}">
    姓名:{{item}}
</view>

hello.js文件:

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
          })
        }
      }
    })
  }
})

app.json:

将hello放到第一行,则首先进入hello.wxml

测试结果如下所示

  点击按钮显示姓名

原文地址:https://www.cnblogs.com/csyzlm/p/11833511.html