在测试阶段,微信小程序是可以请求本地服务器的,这里有如下好处: 1.测试不需要经过网络,暂时可以不配置域名等,服务器也不用上线 2.可以看到小程序和服务器的打印,方便调试和找出问题 3.服务器不用频繁修改上架,更改非常方便
首先要在微信开发者工具做如下配置:
1.勾选上不检测域名: 2.修改请求网址: 3.实现请求代码:
onConfirm: function (res) {
modal.hideModal(this);
console.log("set phone:",this.data.hintinfo.inputValue)
if((this.data.hintinfo.inputValue.length!=11) || isNaN(this.data.hintinfo.inputValue))
{
util.showHintModal("手机号格式错误,请重新输入!");
modal.showDialogBtn(this);
}
else
{
var that = this;
wx.request({
url: util.rootDocment+'/WechatLogin',
data: {
request_id:this.data.hintinfo.inputValue,
request_type: 'wechat'
},
header: {
'content-type': 'application/json'
},
success (res) {
console.log("request_filelist OK")
},
fail:function(err){
console.log(err)
}
})
}
},
微信小程序的配置和修改到这里就结束了,接下来介绍
后端的修改和配置:
1.为微信请求单独实现类WechatLogin,这里获取微信发过来的请求,如下:
package com.wechat.response;
import java.io.IOException;
import java.io.PrintWriter;
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 javax.servlet.http.HttpSession;
import com.util.db;
import com.util.global;
import com.util.StrUtil;
import java.sql.*;
@WebServlet("/WechatLogin")
public class WechatLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
public WechatLogin() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String request_type = (String)request.getParameter("request_type");
String request_id = (String)request.getParameter("request_id");
global.print("request_type:"+request_type);
global.print("request_id:"+request_id);
2.在web.xml增加上servlet的配置
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>WechatLogin</servlet-name>
<servlet-class>com.wechat.response.WechatLogin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WechatLogin</servlet-name>
<url-pattern>/servlet/WechatLogin</url-pattern>
</servlet-mapping>
测试运行:
微信小程序端看到的答应: java后台看到的打印: 测试成功!
|