微信小程序和Java后台进行数据交互

微信小程序和Java后台进行数据交互

1.微信小程序前端准备

微信小程序wxml部分微信小程序和Java后台进行数据交互_第1张图片

<button bindtap="test">测试后台button>
<input class="request" bindinput="getsay">input>
<text class="response">{{getresponse}}text>

2.微信小程序js部分

test:function(e){
    var that = this;
    wx.request({
      url: 'http://localhost:8080/Servlet', //本地服务器地址
      data: { //data中的参数值就是传递给后台的数据
        transInfo: yoursay
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function(res) { //res就是接收后台返回的数据
        that.setData({
          getresponse: res.data
        })
        console.log(res.data);
      },
      fail: function(res) {
        console.log("失败");
      }
    })
  },

3.IDEA后台搭建

架构
微信小程序和Java后台进行数据交互_第2张图片
servlet代码

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 java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

@WebServlet(name = "Servlet", urlPatterns = "/Servlet")
public class Servlet extends HttpServlet{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        /*设置响应头允许ajax跨域访问*/
        response.setHeader("Access-Control-Allow-Origin", "*");

        /* 星号表示所有的异域请求都可以接受, */
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        //获取微信小程序传递的参数值并打印
        //编码转换
        String transInfo = new String(request.getParameter("transInfo").getBytes("iso-8859-1"), "utf-8");
        System.out.println("接收到小程序端传递的数据:" + transInfo);

//        像小程序端传递数据
        response.setHeader("Content-type", "application/json;charset=GBK");
        Writer out = response.getWriter();
        out.write("这是后台给小程序端的数据");
        out.flush();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

4.效果

前台
微信小程序和Java后台进行数据交互_第3张图片
后台
微信小程序和Java后台进行数据交互_第4张图片
完成

https://www.cnblogs.com/lyd447113735/p/13187846.html

你可能感兴趣的:(java,小程序,ajax,servlet)