「小程序JAVA实战」小程序的视频展示页面初始化

进入列表详情,展示点赞状态用户的名称,头像名称。源码:https://github.com/limingios/wxProgram.git 中No.15和springboot

后台开发

拦截器,不拦截获取视频初始化信息。游客可以直接观看。通过用户id,视频id,视频创建id获取是否点赞视频,并获取创建者的信息。

  • 拦截器
package com.idig8;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.idig8.controller.interceptor.MiniInterceptor;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
    @Value("${server.file.path}")
    private String fileSpace;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //资源的路径.swagger2的资源.所在的目录,
        registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/META-INF/resources/")
        .addResourceLocations("file:"+fileSpace);
        
    }


    
    @Bean
    public MiniInterceptor miniInterceptor() {
        return new MiniInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        
        registry.addInterceptor(miniInterceptor()).addPathPatterns("/user/**")
                       .addPathPatterns("/video/upload", "/video/uploadCover","/video/userLike","/video/userUnLike")
                                                  .addPathPatterns("/bgm/**")
                                                  .excludePathPatterns("/user/queryPublisher");
        
        super.addInterceptors(registry);
    }

}

UserController.java

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.PublisherVideo;
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;
import io.swagger.annotations.ApiParam;

@RestController
@Api(value="用户接口",tags={"用户的controller"})
@RequestMapping(value = "/user")
public class UserController extends BasicController{
    
    @Autowired
    private UserService userService;
    
    @Value("${server.file.path}")
    private String fileSpace;
    
    @ApiOperation(value="用户上传头像",notes="用户上传头像的接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name="userId",value="用户id",required=true,dataType="String",paramType="query"),
    })
    @PostMapping(value="/uploadFace",headers="content-type=multipart/form-data")
    public JSONResult uploadFace(String userId,@ApiParam(value="图片",required=true) 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);
    }
    
    @PostMapping("/queryPublisher")
    public JSONResult queryPublisher(String loginUserId, String videoId, 
            String publishUserId) throws Exception {
        
        if (StringUtils.isBlank(publishUserId)) {
            return JSONResult.errorMsg("");
        }
        
        // 1. 查询视频发布者的信息
        Users userInfo = userService.queryUserInfo(publishUserId);
        UsersVO publisher = new UsersVO();
        BeanUtils.copyProperties(userInfo, publisher);
        
        // 2. 查询当前登录者和视频的点赞关系
        boolean userLikeVideo = userService.isUserLikeVideo(loginUserId, videoId);
        
        PublisherVideo bean = new PublisherVideo();
        bean.setPublisher(publisher);   
        bean.setUserLikeVideo(userLikeVideo);
        
        return JSONResult.ok(bean);
    }
    

}

  • service 和 serviceImp
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);
    
    /**
     * 查询用户信息
     */
    public Users queryUserInfo(String userId);
    
    /**
     * 查询用户是否喜欢点赞视频
     */
    public boolean isUserLikeVideo(String userId, String videoId);
    
}

package com.idig8.service.Impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.idig8.mapper.UsersLikeVideosMapper;
import com.idig8.mapper.UsersMapper;
import com.idig8.pojo.Users;
import com.idig8.pojo.UsersLikeVideos;
import com.idig8.service.UserService;
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 UsersLikeVideosMapper usersLikeVideosMapper;
    
    @Autowired
    private UsersMapper userMapper;
    
    @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;
    }
    
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserInfo(String userId) {
        Example userExample = new Example(Users.class);
        Criteria criteria = userExample.createCriteria();
        criteria.andEqualTo("id", userId);
        Users user = userMapper.selectOneByExample(userExample);
        return user;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean isUserLikeVideo(String userId, String videoId) {

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(videoId)) {
            return false;
        }
        
        Example example = new Example(UsersLikeVideos.class);
        Criteria criteria = example.createCriteria();
        
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("videoId", videoId);
        
        List<UsersLikeVideos> list = usersLikeVideosMapper.selectByExample(example);
        
        if (list != null && list.size() >0) {
            return true;
        }
        
        return false;
    }

}

小程序修改

  • videoInfo.js
var videoUtils = require('../../utils/videoUtils.js')
const app = getApp()
Page({

  data: {
    cover:'cover',
    videoContext:"",
    videoInfo:{},
    videId:'',
    src:'',
    userLikeVideo:false,
    serverUrl:'',
    publisher:[]
  },
  

  showSearch:function(){
    wx.navigateTo({
      url: '../videoSearch/videoSearch',
    })
  },
  onLoad:function(params){
    var me = this;
    me.videoContext = wx.createVideoContext('myVideo', me);
    var videoInfo = JSON.parse(params.videoInfo);
    var videoWidth = videoInfo.videoWidth;
    var videoHeight = videoInfo.videoHeight;
    var cover = 'cover';
    if (videoWidth > videoHeight){
      cover = '';
    }
    me.setData({
      videId: videoInfo.id,
      src: app.serverUrl + videoInfo.videoPath,
      videoInfo: videoInfo,
      cover: cover
    })

    var serverUrl = app.serverUrl;
    var user = app.getGlobalUserInfo();
    var loginUserId = "";
    if (user != null && user != undefined && user != '') {
      loginUserId = user.id;
    }
    wx.request({
      url: serverUrl + '/user/queryPublisher?loginUserId=' + loginUserId + "&videoId=" + videoInfo.id + "&publishUserId=" + videoInfo.userId,
      method: 'POST',
      success: function (res) {
        console.log(res.data);

        var publisher = res.data.data.publisher;
        var userLikeVideo = res.data.data.userLikeVideo;

        me.setData({
          serverUrl: serverUrl,
          publisher: publisher,
          userLikeVideo: userLikeVideo
        });
      }
    })




  },
  showIndex:function(){
    wx.redirectTo({
      url: '../index/index',
    })
  },

  onShow:function(){
    var me = this;
    me.videoContext.play();
  },
  onHide:function(){
    var me = this;
    me.videoContext.pause();
  },
  upload:function(){
 
    var me = this;
    var userInfo = app.getGlobalUserInfo();

    var videoInfo = JSON.stringify(me.data.videoInfo);
    var realUrl = '../videoInfo/videoInfo#videoInfo@' + videoInfo;

    if (userInfo.id == '' || userInfo.id == undefined) {
      wx.navigateTo({
        url: '../userLogin/userLogin?realUrl=' + realUrl,
      })
    } else {
      videoUtils.uploadVideo();
    }


  },
  showMine: function () {
    var me = this;
    var userInfo = app.getGlobalUserInfo();

    var videoInfo = JSON.parse

    if (userInfo.id == '' || userInfo.id == undefined){
      wx.navigateTo({
        url: '../userLogin/userLogin',
      })
    }else{
      wx.navigateTo({
        url: '../mine/mine',
      })
    }
    
   
  },

  likeVideoOrNot: function () {
    var me = this;
    var userInfo = app.getGlobalUserInfo();


    var videoInfoStr = JSON.stringify(me.data.videoInfo);
    var realUrl = '../videoInfo/videoInfo#videoInfo@' + videoInfoStr;
    if (userInfo.id == '' || userInfo.id == undefined) {
      wx.navigateTo({
        url: '../userLogin/userLogin?realUrl=' + realUrl,
      })
    } else {
      var videoInfo = me.data.videoInfo;
      var userLikeVideo = me.data.userLikeVideo;
      var url = "/video/userLike?userId=" + userInfo.id + "&videoId=" + videoInfo.id + "&videoCreaterId=" + userLikeVideo.userId;

      if (userLikeVideo){
        var url = "/video/userUnLike?userId=" + userInfo.id + "&videoId=" + videoInfo.id + "&videoCreaterId=" + userLikeVideo.userId;
      }
      wx.showLoading({
        title: '....',
      })
      wx.request({
        url: app.serverUrl + url,
        method: "POST",
        header: {
          'content-type': 'application/json', // 默认值
          'headerUserId': userInfo.id,
          'headerUserToken': userInfo.userToken
        },
        success: function (res) {
          wx.hideLoading();
          me.setData({
            userLikeVideo: !userLikeVideo,
          })
        }
      })

    }


  }
})

PS:拦截器excludePathPatterns可以不拦截,分析业务,那些需要登录后才可以获得,那些不需要登录就可以看到。

老规矩,先看本节效果图 我们实现这个支付功能完全是借助小程序云开发实现的,不用搭建自己的服务器,不用买域名,不用备案域名,不用支持https。只需要一个简单的云函数,就可以轻松的实现微信小程序支付功能。 核心代码就下面这些 一,创建一个云开发小程序 关于如何创建云开发小程序,这里我就不再做具体讲解。不知道怎么创建云开发小程序的同学,可以去翻看我之前的文章,或者看下我录制的视频:https://edu.csdn.net/course/play/9604/204528 创建云开发小程序有几点注意的 1,一定不要忘记在app.js里初始化云开发环境。 2,创建完云函数后,一定要记得上传 二, 创建支付的云函数 1,创建云函数pay 三,引入三方依赖tenpay 我们这里引入三方依赖的目的,是创建我们支付时需要的一些参数。我们安装依赖是使用里npm 而npm必须安装node,关于如何安装node,我这里不做讲解,百度一下,网上一大堆。 1,首先右键pay,然后选择在终端中打开 2,我们使用npm来安装这个依赖。 在命令行里执行 npm i tenpay 安装完成后,我们的pay云函数会多出一个package.json 文件 到这里我们的tenpay依赖就安装好了。 四,编写云函数pay 完整代码如下 //云开发实现支付 const cloud = require('wx-server-sdk') cloud.init() //1,引入支付的三方依赖 const tenpay = require('tenpay'); //2,配置支付信息 const config = { appid: '你的小程序appid', mchid: '你的微信商户号', partnerKey: '微信支付安全密钥', notify_url: '支付回调网址,这里可以先随意填一个网址', spbill_create_ip: '127.0.0.1' //这里填这个就可以 }; exports.main = async(event, context) => { const wxContext = cloud.getWXContext() let { orderid, money } = event; //3,初始化支付 const api = tenpay.init(config); let result = await api.getPayParams({ out_trade_no: orderid, body: '商品简单描述', total_fee: money, //订单金额(分), openid: wxContext.OPENID //付款用户的openid }); return result; } 一定要注意把appid,mchid,partnerKey换成你自己的。 到这里我们获取小程序支付所需参数的云函数代码就编写完成了。 不要忘记上传这个云函数。 出现下图就代表上传成功 五,写一个简单的页面,用来提交订单,调用pay云函数。 这个页面很简单, 1,自己随便编写一个订单号(这个订单号要大于6位) 2,自己随便填写一个订单价(单位是分) 3,点击按钮,调用pay云函数。获取支付所需参数。 下图是官方支付api所需要的一些必须参数。 下图是我们调用pay云函数获取的参数,和上图所需要的是不是一样。 六,调用wx.requestPayment实现支付 下图是官方的示例代码 这里不在做具体讲解了,完整的可以看视频。 实现效果 1,调起支付键盘 2,支付完成 3,log日志,可以看出不同支付状态的回调 上图是支付成功的回调,我们可以在支付成功回调时,改变订单支付状态。 下图是支付失败的回调, 下图是支付完成的状态。 到这里我们就轻松的实现了微信小程序的支付功能了。是不是很简单啊,完整的讲解可以看视频
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:上身试试 返回首页