最近领导布置了小程序任务,开始做一个设备维护保养的项目对应小程序,前几天在画静态界面,一直以为很简单的事,真正做起来发现,想要做的好看好用还是挺不容易的。
今天开始做系统登录,因为要喝网页版应用同样数据库,所以把接口也写到了网页版工程中,后台为java接口,整个时序图网上查下很常见,api中也有。以下是我初步实现应用后台java接口获取openid和session_key返回,后面的应用实现随时补充,也是自己一个人在摸索,身边也没有可以请教的大神,感觉这个过程还是遇到不少坑,慢慢学习吧,多总结多试。
小程序部分:
my.wxml
系统登录
my.wxss
page{
height: 100%;
color: #333;
display: flex;
flex-direction: column;
font: normal 30rpx/1.68 -apple-system-font, 'Helvetica Neue', Helvetica, 'Microsoft YaHei', sans-serif;
}
.container {
flex: 1;
display: flex;
flex-direction: column;
box-sizing: border-box;
background-color: #fafafa;
}
.my-item{
border-bottom: 10rpx solid #fafafa;
height: 50rpx;
padding: 20rpx;
/* background: #fff 98% 50% / auto 100rpx; */
background: #fff;
display: flex;
flex-direction: row;
position: relative;
}
.my-item-image{
width:50px;
height:50px;
margin:10rpx 0 0 10rpx;
float:left
}
.my-item-text{
margin-left:150rpx;
padding-top:-12px;
font-size:38rpx;
color:#656565;
height:60px;
display:block;
line-height:60px;
}
.com-btn{
height:40px;
width:500rpx;
margin-top:20px;
font-color:#fff;
background-color: #00aeee !important;
}
my.json:因为界面模版应用了vant,所以应用了登录输入的模版,怎么应用在api中有,直接拿来用:
{
"navigationBarTitleText": "我的",
"usingComponents": {
"van-field": "../../dist/field/index"
}
}
my.js
//获取应用实例
var app = getApp();
var requestUrl = app.globalData.requestUrl;
Page({
data: {
username: "",//输入用户名
password: "",//输入密码
},
//输入用户名
usernameinput: function(e) {
this.setData({
username: e.detail
})
},
//输入密码
passwordinput: function(e) {
this.setData({
password: e.detail
})
},
//点击登陆的时候触发的事件
login: function() {
var that = this;
//登陆的时候要传过来的参数
var name = that.data.username;
var pwd = that.data.password;
if (that.data.username == "") {
wx.showModal({
title: "信息提示",
content: "用户名不能为空!"
})
} else if (that.data.password == "") {
wx.showModal({
title: "信息提示",
content: "请输入密码!"
})
}
console.log("用户名:" + name + "密码:" + pwd)
//微信登录
wx.login({
success: function(res) {
if (res.code) {
console.log("code=" + res.code)
//发送ajax请求到服务器-登录
wx.request({
url: requestUrl,
data: {
userName: name,
password: pwd,
code: res.code,
operFlag: 'getOpenid',
},
header: {
'content-type': 'application/x-www-form-urlencoded' // 默认值
},
method: 'POST',
dataType: 'json',
success: function(res) {
console.log(res)
var status = JSON.stringify(res.data.status)
var msg = JSON.stringify(res.data.msg)
//弹出提示
// wx.showModal({
// title: "信息提示",
// content: msg
// })
if (status == 0) {
//跳转到index页面
wx.switchTab({
url: '../index/index',
})
}
},
fail: function(res) {
wx.showToast({
title: '服务器网络错误,请稍后重试',
icon: 'loading',
duration: 1500
})
},
complete: function(res) {
},
})
}
}
})
},
})
app.js:在这里定义了访问接口路径,我是在本地试,需要点击详情,最下方“不校验合法域名。。”打上勾。
java接口:
在web.xml中添加
WechatService
com.sibdp.portal.servlet.WechatServlet
WechatService
/wechat
servlet
package com.sibdp.portal.servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import com.cattsoft.framework.exception.SysException;
import com.cattsoft.system.service.ISysUserService;
public class WechatServlet extends HttpServlet {
private Logger logger = LoggerFactory.getLogger(WechatServlet.class);
@Autowired
private ISysUserService sysUserService;
private static final String APPID = "wxf7c1b1a493e153e4";//后续修改为对应APPID
private static final String SECRET = "e302ee388a5c65710e49a5aff883e2c5";
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext());
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
logger.info("调用doGet方法");
this.doPost(req, resp);
}
/**
* 微信小程序调用接口
* @param request,password,response
* @return String
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.debug("*******调用接口*********");
String userName = request.getParameter("userName");//登录用户名
String password = request.getParameter("password");//加密密码
// String code = request.getParameter("code");//小程序临时登录凭证
String operFlag = request.getParameter("operFlag");
logger.debug("userName="+userName+";password="+password+";");
String results = "";
RestTemplate restTemplate = new RestTemplate();
//进行网络请求,访问url接口
// ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
try {
if("getOpenid".equals(operFlag)){
String code = request.getParameter("code"); //拿到微信小程序传过来的code
System.out.println(code);
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID + "&secret=" + SECRET
+ "&js_code=" + code + "&grant_type=authorization_code"; //接口地址
System.out.println("url:"+url);
results = sendGetReq(url);// 发送http请求
System.out.println("results"+results);
}
} catch (SysException e) {
e.printStackTrace();
}
response.setContentType("application/json;charset=UTF-8");
response.setHeader("catch-control", "no-catch");
PrintWriter pw = response.getWriter();
pw.print(results);
pw.flush();
pw.close();
}
private String sendGetReq(String url) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
java.util.Map> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
} // 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}