試水微信小程序與Java後臺通信

寫在前面

Client: 微信小程序

Server: Java Servlet running on local Tomcat 9.0

Tools: 微信開發者工具 && Eclipse

Client

弄一個簡陋的微信小程序進行測試,wxml 只需要繪製一個向後臺發送信息的按鈕即可:

<!--index.wxml-->
<view class="container">
  <button bindtap='connecttest'>test</button>
</view>

在 js 中綁定按鍵發送請求並在 console 中輸出返回值:

//index.js
//獲取應用實例
const app = getApp()
Page({
  connecttest: function () {
    wx.request({
      url: 'http://localhost:8080/smallAPP/ConnectTest',
      data: {
        username: 'pomo',
        password: '123'
      },
      method: 'POST',
      header: {
        //'content-type': 'application/json' // 默認值以 json 形式發送請求
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data);
      },
      fail: function (res) {
        console.log("Fail to connect...");
      }
    })
  }
)}

到目前爲止,Client 已經完成。

Server

lib

在 Eclipse 中新建一個名叫 smallApp 的 Dynamic Web Project 。先在 WEB-INF 的 lib 中導入 json 相關包:json-lib-2.4-jdk15.jar download

但是這裏要注意一個陷阱,這個 json 包需要依賴其他包才能正常運行:

  • jakarta commons-lang 2.5

  • jakarta commons-beanutils 1.8.0

  • jakarta commons-collections 3.2.1

  • jakarta commons-logging 1.1.1

  • ezmorph 1.0.6

官方網址:http://json-lib.sourceforge.net/

DTO

定義一個名叫 user 的 DTO 並帶有 userName 和 password 兩個屬性:

package com.smallAPP.common;

public class User {
	private String userName;
	private String password;
	public User() {
		super();
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

Servlet

在 DTO 的同一目錄下新建一個 Servlet:

package com.smallAPP.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

@WebServlet("/ConnectTest")
public class ConnectTest extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public ConnectTest() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
        //設置請求編碼
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        /* 設置響應頭允許ajax跨域訪問 */
        //response.setHeader("Access-Control-Allow-Origin", "*");
        /* 星號表示所有的異域請求都可以接受, */
        //response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        User user = new User();
        //獲取微信小程序get的參數值並打印
        user.setUserName(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        System.out.println("username="+user.getUserName()+" ,password="+user.getPassword());
        //轉成json數據
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("data", user);
        result.put("msg", "後臺已收到");
        JSONObject object = JSONObject.fromObject(result);
        PrintWriter out = response.getWriter();
		out.print(object.toString());
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

這個 Servlet 的功能就是把 Client 發送過來的 userName 和 password 在控制檯輸出,然後把這兩個信息轉換成 json 數據返回給微信小程序。

測試

在微信開發者工具詳情中設置不校驗域名(若非本地服務器測試,需要配置好服務器,服務器配置好之後無需關心跨域問題):

在 Eclipse 運行 Servlet,然後點擊微信小程序頁面上的 test 按鈕向後臺發送請求,在 Eclipse 中查看後臺的接收結果:

然後再觀察微信小程序的 console:

如上圖所示,微信小程序與 Java 後臺成功進行通訊。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章