微信小程序開發——后端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

 

測試結果如下所示

  點擊按鈕顯示姓名

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM