小程序
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
wx.request({
url: 'http://localhost:8080/Demo/regis',
data: '',
header: {},
method: 'GET',
dataType: 'json',
responseType: 'text',
success: function(res) {
console.log(res)
},
fail: function(res) {},
complete: function(res) {},
})
},
servlet
public class regisServlet extends HttpServlet {
public void init() throws ServletException {
}
public 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");
// 设置响应
response.setContentType("text/html");
/*
* 实际逻辑处理
*/
// 获取页面(小程序)传值
String pageValue = request.getParameter("testVal");
System.out.print("来自页面的值:" + pageValue);
// 向页面(小程序)返回值
String[] color = { "黑色", "白色", "蓝色" };
// 转成json数据 使用Gson类需要导入gson-2.8.0.jar
Map<String, Object> result = new HashMap<String, Object>();
result.put("data", color);
result.put("msg", "成功");
String json = new Gson().toJson(result);
// 返回值给微信小程序
Writer out = response.getWriter();
out.write(json);
out.flush();
}
// 结束
public void destroy() {
}
}
GSON下载: http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5">
<servlet>
<servlet-name>regisServlet</servlet-name>
<servlet-class>com.demo.user.regisServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>regisServlet</servlet-name>
<url-pattern>/regis</url-pattern>
</servlet-mapping>
</web-app>
页面接收
后台接收
原作者地址:https://blog.csdn.net/code_shadow/article/details/80372516