接下来,我们应该通过用户的id,调用后端的接口,查询出来点赞的数量,关注的数量,粉丝数量,直接更新头像图片。源码:https://github.com/limingios/wxProgram.git 中wx-springboot 和 No.15
spring boot-service 增加通过user的id,获得Users的方法
package com.idig8.service;
import com.idig8.pojo.Users;
public interface UserService {
/**
* 判断用户名是否存在
* @param username
* @return
*/
public boolean queryUsernameIsExist(String username);
/**
* 保存用户
* @param user
* @return
*/
public void saveUser(Users user);
/**
* 查询用户对象
* @param username
* @return
*/
public Users queryUserIsExist(Users user);
/**
* 更新对象
* @param username
* @return
*/
public void updateUser(Users user);
/**
* userId查询用户对象
* @param username
* @return
*/
public Users queryUserId(String userId);
}
package com.idig8.service;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.idig8.mapper.UsersMapper;
import com.idig8.pojo.Users;
import com.idig8.utils.MD5Utils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UsersMapper usersMapper;
@Autowired
private Sid sid;
@Transactional(propagation =Propagation.SUPPORTS)
@Override
public boolean queryUsernameIsExist(String username) {
Users user = new Users();
user.setUsername(username);
Users result = usersMapper.selectOne(user);
return result==null? false:true;
}
@Transactional(propagation =Propagation.REQUIRED)
@Override
public void saveUser(Users user) {
String userId =sid.nextShort();
user.setId(userId);
usersMapper.insert(user);
}
@Transactional(propagation =Propagation.SUPPORTS)
@Override
public Users queryUserIsExist(Users user) {
Example queryExample = new Example(Users.class);
Criteria criteria = queryExample.createCriteria();
criteria.andEqualTo("username",user.getUsername());
try {
criteria.andEqualTo("password",MD5Utils.getMD5Str(user.getPassword()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Users userOne = usersMapper.selectOneByExample(queryExample);
return userOne;
}
@Transactional(propagation =Propagation.REQUIRED)
@Override
public void updateUser(Users user) {
Example userExample = new Example(Users.class);
Criteria criteria = userExample.createCriteria();
criteria.andEqualTo("id", user.getId());
usersMapper.updateByExampleSelective(user, userExample);
}
@Transactional(propagation =Propagation.SUPPORTS)
@Override
public Users queryUserId(String userId){
Example queryExample = new Example(Users.class);
Criteria criteria = queryExample.createCriteria();
criteria.andEqualTo("id",userId);
Users userOne = usersMapper.selectOneByExample(queryExample);
return userOne;
}
}
增加controller 接口,传递user中的id参数
package com.idig8.controller;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.idig8.pojo.Users;
import com.idig8.pojo.vo.UsersVO;
import com.idig8.service.UserService;
import com.idig8.utils.JSONResult;
import com.idig8.utils.file.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
@RestController
@Api(value="用户接口",tags={"用户的controller"})
@RequestMapping(value = "/user")
public class UserController extends BasicController{
@Autowired
private UserService userService;
@Value("${server.face.path}")
private String fileSpace;
@ApiOperation(value="用户上传头像",notes="用户上传头像的接口")
@ApiImplicitParams({
@ApiImplicitParam(name="userId",value="用户id",required=true,dataType="String",paramType="query"),
@ApiImplicitParam(name="file",value="文件上传",required=true,dataType="String",paramType="query"),
})
@PostMapping("/uploadFace")
public JSONResult uploadFace(String userId,@RequestParam("file") MultipartFile file) {
if (StringUtils.isBlank(userId)) {
return JSONResult.errorMsg("用户id不能为空...");
}
// 文件保存的命名空间
String fileName = file.getOriginalFilename();
// 保存到数据库中的相对路径
String path = "";
try {
path = FileUtil.uploadFile(file.getBytes(), fileSpace, fileName);
} catch (Exception e) {
e.getStackTrace();
return JSONResult.errorMsg(e.getMessage());
}
Users user = new Users();
user.setId(userId);
user.setFaceImage(path);
userService.updateUser(user);
return JSONResult.ok(path);
}
@ApiOperation(value="通过用户Id获取用户信息",notes="通过用户Id获取用户信息的接口")
@ApiImplicitParam(name="userId",value="用户id",required=true,dataType="String",paramType="query")
@PostMapping("/queryByUserId")
public JSONResult queryByUserId(String userId) {
if (StringUtils.isBlank(userId)) {
return JSONResult.errorMsg("用户id不能为空...");
}
Users user = userService.queryUserId(userId);
UsersVO usersVO= new UsersVO();
BeanUtils.copyProperties(user, usersVO);
return JSONResult.ok(usersVO);
}
}
主要通过的是小程序生命周期中的onload方法,当进入页面的时候请求后台获取信息,用于页面的展示。
// pages/mine/mine.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
faceImage: "../../resource/images/noneface.png",
nickname: "昵称",
fansCounts: 0,
followCounts: 0,
receiveLikeCounts: 0,
},
/**
* 用户注销
*/
logout:function(e){
var user = app.userInfo;
wx.showLoading({
title: '正在注销中。。。'
});
wx.request({
url: app.serverUrl + "/logout?userId="+user.id,
method: "POST",
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data);
var status = res.data.status;
wx.hideLoading();
if (status == 200) {
wx.showToast({
title: "用户注销成功~!",
icon: 'none',
duration: 3000
})
app.userInfo = null;
wx.redirectTo({
url: '../userRegister/userRegister',
})
} else if (status == 500) {
wx.showToast({
title: res.data.msg,
icon: 'none',
duration: 3000
})
}
}
})
},
/**
* 头像上传
*/
uploadFace:function(e){
var user = app.userInfo;
var me = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths
if (tempFilePaths.length>0){
console.log(tempFilePaths[0]);
wx.uploadFile({
url: app.serverUrl + "/user/uploadFace?userId=" + user.id, //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
success: function (res) {
var data = JSON.parse(res.data);
console.log(data);
wx.hideLoading();
if (data.status == 200) {
wx.showToast({
title: "用户上传成功~!",
icon: 'none',
duration: 3000
})
me.setData({
faceUrl: app.serverUrl+data.data
})
} else if (data.status == 500) {
wx.showToast({
title: data.msg,
icon: 'none',
duration: 3000
})
}
}
})
}
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var me = this;
wx.showLoading({
title: '正在获取用户信息。。。'
});
wx.request({
url: app.serverUrl + "/user/queryByUserId?userId=" + app.userInfo.id,
method: "POST",
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data);
var status = res.data.status;
var userInfo = res.data.data;
wx.hideLoading();
var faceImage = me.data.faceUrl;
if (userInfo.faceImage != null && userInfo.faceImage != '' && userInfo.faceImage!=undefined){
faceImage = app.serverUrl +userInfo.faceImage;
}
me.setData({
faceImage: faceImage,
fansCounts: userInfo.fansCounts,
followCounts: userInfo.followCounts,
receiveLikeCounts: userInfo.receiveLikeCounts,
nickname: userInfo.nickname
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
PS:这个小程序获取用户信息和后端的一个联调。