栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

「小程序JAVA实战」小程序搜索功能(55)

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

「小程序JAVA实战」小程序搜索功能(55)

通过用户搜索热销词,将热销词添加到数据库中,搜索页面通过热销词的频率展示出来那些词属于热销词。并添加列表参数,可以通过搜索关键字查询列表功能。源码:https://github.com/limingios/wxProgram.git 中wx-springboot 和 No.15

后台接口的开发。
  • 增加关键字查询视频列表功能

VideosUserMapper.xml




  
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  

  
    select v.*,u.face_image,u.username,u.nickname from videos v
    left join users u on v.user_id = u.id
    where 
        1 = 1
        
            and v.video_desc like '%${videoDesc}%'
        
        and v.status = 1
    order by v.create_time

  

  • 热销词统计功能
    SearchRecordsMapper.xml




  
    
    
    
  

  
    select content from search_records group by content order by count(content) desc
  
  • java对应xml的方法
    VideosUsersMapper.java

package com.idig8.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.idig8.pojo.Videos;
import com.idig8.pojo.vo.VideosVO;
import com.idig8.utils.MyMapper;

public interface VideosUsersMapper extends MyMapper {

    public List queryAllVideos(@Param("videoDesc") String videoDesc);
}

SearchRecordsMapper.java

package com.idig8.mapper;

import java.util.List;

import com.idig8.pojo.SearchRecords;
import com.idig8.utils.MyMapper;

public interface SearchRecordsMapper extends MyMapper {

    public List gethotList();
}
  • service 添加2个方法,
    >列表中添加保存关键字,查询视频添加关键字的,
    >获取热销词列表

VideoService.java

package com.idig8.service;

import java.util.List;

import com.idig8.pojo.Videos;
import com.idig8.utils.PagedResult;

public interface VideoService {


    
    public String saveVideo(Videos video);

    
    public PagedResult getAllVideos(Videos video,Integer isSaveRecord,Integer page,Integer pageSize);

    
    public List gethostList();
}

VideoServiceImpl.java

package com.idig8.service.Impl;

import java.util.List;

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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import com.idig8.mapper.SearchRecordsMapper;
import com.idig8.mapper.VideosMapper;
import com.idig8.mapper.VideosUsersMapper;
import com.idig8.pojo.SearchRecords;
import com.idig8.pojo.Videos;
import com.idig8.pojo.vo.VideosVO;
import com.idig8.service.VideoService;
import com.idig8.utils.PagedResult;

@Service
public class VideoServiceImpl implements  VideoService {

    @Autowired
    private VideosMapper videosMapper;

    @Autowired
    private VideosUsersMapper videosUsersMapper;

    @Autowired
    private SearchRecordsMapper searchRecordsMapper;

    @Autowired
    private Sid sid;

    @Transactional(propagation =Propagation.REQUIRED)
    public String  saveVideo(Videos video){
        String id = sid.nextShort();
        video.setId(id);

        videosMapper.insertSelective(video);
        return id;


    }

    @Override
    @Transactional(propagation =Propagation.REQUIRED)
    public PagedResult getAllVideos(Videos video,Integer isSaveRecord,Integer page, Integer pageSize) {

        String desc = video.getVideoDesc();
        if(isSaveRecord!=null && isSaveRecord ==1){
            SearchRecords record = new SearchRecords();
            String recordId = sid.nextShort();
            record.setId(recordId);
            record.setContent(desc);
            searchRecordsMapper.insert(record);
        }

        PageHelper.startPage(page,pageSize);
        List list = videosUsersMapper.queryAllVideos(desc);
        PageInfo pageList =new PageInfo<>(list);

        PagedResult result = new PagedResult();
        result.setPage(page);
        result.setTotal(pageList.getPages());
        result.setRows(list);
        result.setRecords(pageList.getTotal());

        return result;
    }

    @Transactional(propagation =Propagation.SUPPORTS)
    @Override
    public List gethostList() {

        return searchRecordsMapper.gethotList();
    }
}
  • controller 控制器开发

package com.idig8.controller;

import java.io.File;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.idig8.pojo.Bgm;
import com.idig8.pojo.Videos;
import com.idig8.service.BgmService;
import com.idig8.service.VideoService;
import com.idig8.utils.FetchVideoCover;
import com.idig8.utils.JSONResult;
import com.idig8.utils.MergeVideoMp3;
import com.idig8.utils.PagedResult;
import com.idig8.utils.enums.VideoStatusEnum;
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("/video")
public class VideoController extends BasicController {

    @Autowired
    private BgmService bgmService;

    @Autowired
    private VideoService videosService;

    @Value("${server.file.path}")
    private String fileSpace;

    @Value("${server.ffmpeg.path}")
    private String ffmpegexe;


    @ApiOperation(value="上传视频", notes="上传视频的接口")
    @ApiImplicitParams({
        @ApiImplicitParam(name="userId", value="用户id", required=true, 
                dataType="String", paramType="form"),
        @ApiImplicitParam(name="bgmId", value="背景音乐id", required=false, 
                dataType="String", paramType="form"),
        @ApiImplicitParam(name="videoSeconds", value="背景音乐播放长度", required=true, 
                dataType="String", paramType="form"),
        @ApiImplicitParam(name="videoWidth", value="视频宽度", required=true, 
                dataType="String", paramType="form"),
        @ApiImplicitParam(name="videoHeight", value="视频高度", required=true, 
                dataType="String", paramType="form"),
        @ApiImplicitParam(name="desc", value="视频描述", required=false, 
                dataType="String", paramType="form")
    })
    @PostMapping(value="/upload", headers="content-type=multipart/form-data")
    public JSONResult upload(String userId, 
                String bgmId, double videoSeconds, 
                int videoWidth, int videoHeight,
                String desc,
                @ApiParam(value="短视频", required=true)
                MultipartFile file) throws Exception {

        if (StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("用户id不能为空...");
        }
        // 文件保存的命名空间
        String fileName = file.getOriginalFilename();
        // 保存到数据库中的相对路径
        String path = "";
        String videOutPath = "";
        String ImagePath = "";
        try {
             path = FileUtil.uploadFile(file.getBytes(), fileSpace, fileName);
            } catch (Exception e) {
                e.getStackTrace();
                   return JSONResult.errorMsg(e.getMessage());
            }                


        if(StringUtils.isNotBlank(bgmId)){
            Bgm bgm = bgmService.queryBgmById(bgmId);
            String mp3BgmPath = fileSpace + bgm.getPath();
            MergeVideoMp3 mergeVideoMp3 = new MergeVideoMp3(ffmpegexe);
            String videOutPathName = UUID.randomUUID().toString()+".mp4";
            File targetFile = new File(fileSpace + userId);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            videOutPath = "/"+userId+"/"+videOutPathName;
            String videoInput = fileSpace +path;
            mergeVideoMp3.convertor(videoInput, mp3BgmPath, videoSeconds, fileSpace +videOutPath);

        }else{
            videOutPath = path;

        }

        ImagePath =  "/"+userId+"/"+UUID.randomUUID().toString()+".jpg";;
        FetchVideoCover fetchVideoCover = new FetchVideoCover(ffmpegexe);
        fetchVideoCover.getCover(fileSpace +videOutPath, fileSpace +ImagePath);


        Videos videos = new Videos();
        videos.setAudioId(bgmId);
        videos.setCreateTime(new Date());
        videos.setVideoDesc(desc);
        videos.setId(UUID.randomUUID().toString());
        videos.setUserId(userId);
        videos.setVideoHeight(videoHeight);
        videos.setVideoWidth(videoWidth);
        videos.setVideoPath(videOutPath);
        videos.setCoverPath(ImagePath);
        videos.setStatus(VideoStatusEnum.SUCCESS.value);
        videosService.saveVideo(videos);

        return JSONResult.ok(path);

    }

    @PostMapping(value="/showAll")
    @ApiOperation(value="视频列表", notes="分页的视频列表")
    public JSONResult upload(@RequestBody Videos video,Integer isSaveRecord,
            Integer page) throws Exception {
        if(page == null){
            page = 1;
        }
        PagedResult result = videosService.getAllVideos(video,isSaveRecord,page, PAGE_SIZE);     
        return JSONResult.ok(result);

    }

    @PostMapping(value="/hot")
    @ApiOperation(value="热搜词列表", notes="热搜词列表")
    public JSONResult upload() throws Exception {

        return JSONResult.ok(videosService.gethostList());

    }
}

前端功能开发

调后端url,获取热销关键字展示。

var WxSearch = require('../../wxSearchView/wxSearchView.js');
const app = getApp()
Page({

  
  data: {

  },

  onLoad: function () {


    // 2 搜索栏初始化
    var that = this;
    wx.request({
      url: app.serverUrl +"/video/hot",
      method: "POST",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var searchHot = res.data.data;
        WxSearch.init(
          that,  // 本页面一个引用
          searchHot, // 热点搜索推荐,[]表示不使用
          searchHot,// 搜索匹配,[]表示不使用
          that.mySearchFunction, // 提供一个搜索回调函数
          that.myGobackFunction //提供一个返回回调函数
        );
      }
    })



  },

  // 3 转发函数,固定部分,直接拷贝即可
  wxSearchInput: WxSearch.wxSearchInput,  // 输入变化时的操作
  wxSearchKeyTap: WxSearch.wxSearchKeyTap,  // 点击提示或者关键字、历史记录时的操作
  wxSearchDeleteAll: WxSearch.wxSearchDeleteAll, // 删除所有的历史记录
  wxSearch/confirm/i: WxSearch.wxSearch/confirm/i,  // 搜索函数
  wxSearchClear: WxSearch.wxSearchClear,  // 清空函数

  // 4 搜索回调函数  
  mySearchFunction: function (value) {
    // do your job here
    // 示例:跳转
    wx.redirectTo({
      url: '../index/index?isSaveRecord=1&searchValue=' + value
    })
  },

  // 5 返回回调函数
  myGobackFunction: function () {
    // do your job here
    // 示例:返回
    wx.redirectTo({
      url: '../index/index'
    })
  },

  
  onReady: function () {

  },

  
  onShow: function () {

  },

  
  onHide: function () {

  },

  
  onUnload: function () {

  },

  
  onPullDownRefresh: function () {

  },

  
  onReachBottom: function () {

  },

  
  onShareAppMessage: function () {

  }
})

  • 输入搜索后跳转到index页面,展示搜索结果
    >增加isSaveRecord 和 searchValue 关键字根据搜索传递过来,然后修改请求列表参数。

const app = getApp()

Page({
  data: {
    // 用于分页的属性
    totalPage: 1,
    page: 1,
    videoList: [],
    screenWidth: 350,
    serverUrl: "",
    searchValue:""
  },

  onLoad: function (params) {
    var me = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;
    me.setData({
      screenWidth: screenWidth,
    });

    var searchValue = params.searchValue;
    var isSaveRecord = params.isSaveRecord;
    if (isSaveRecord == null || isSaveRecord == "" || isSaveRecord == undefined){
      isSaveRecord = 0;
    }

    me.setData({
      searchValue: searchValue,
    });



    // 获取当前的分页数
    var page = me.data.page;
    me.getAllVideosList(page, isSaveRecord);
  },

  getAllVideosList: function (page, isSaveRecord){
    var me = this;
    var serverUrl = app.serverUrl;
    wx.showLoading({
      title: '请等待,加载中...',
    });


    wx.request({
      url: serverUrl + '/video/showAll?page=' + page + "&isSaveRecord =" + isSaveRecord,
      method: "POST",
      data:{
        videoDesc: me.data.searchValue
      },
      success: function (res) {
        wx.hideLoading();
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();

        console.log(res.data);

        // 判断当前页page是否是第一页,如果是第一页,那么设置videoList为空
        if (page === 1) {
          me.setData({
            videoList: []
          });
        }

        var videoList = res.data.data.rows;
        var newVideoList = me.data.videoList;

        me.setData({
          videoList: newVideoList.concat(videoList),
          page: page,
          totalPage: res.data.data.total,
          serverUrl: serverUrl
        });

      }
    })
  },

  onPullDownRefresh: function (params) {
    var me = this;
    wx.showNavigationBarLoading();
    me.getAllVideosList(1,0);

  },

  onReachBottom: function (params){
    var me = this;
    var currentPage = me.data.page;
    var totalPage = me.data.totalPage;

    //判断当前页数和总页数是否相等,如果相同已经无需请求
    if (currentPage == totalPage){
      wx.showToast({
        title: '已经没有视频啦~',
        icon:"none"
      })
      return;
    }
    var page = currentPage+1;
    me.getAllVideosList(page,0);

}


})

PS:搜索功能,后台提供url,直接赋值到插件就可以了,通过输入关键字点击搜索,将关键字保存标识传递,关键字传递给index页面,index获取后在根据关键字查询结果。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/234907.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号