微信小程序实战 (微信小程序实现图书查询功能)

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 微信小程序实战 (微信小程序实现图书查询功能)

上一篇简单的写了个微信小程序调用后端接口的demo,这一篇在此基础上做一个通过小程序调用后端实现图书查询功能。

1.思路

在前端输入框输入图书信息,通过bindtap事件获取输入的关键字,点击搜索时调用后端接口传入关键字进行查询。然后根据返回的数据进行遍历展示。

2.后端代码

gitee地址

2.1 导入依赖

导入lombok依赖 自动生成get、set、有无参构造方法

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

导入数据库相关依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

使用mtbatisX插件生成代码 ,参考:上一篇:mybatisx 插件的踩坑使用

生成Book实体类文件

package com.ctsi.sddx.pojo;
import java.io.Serializable;
import java.math.BigDecimal;
import lombok.Data;
/**
 * 
 * @TableName xcx_book
 */
@Data
public class XcxBook implements Serializable {
    /**
     * 编号
     */
    private Integer id;
    /**
     * 图书名称
     */
    private String title;
    /**
     * 作者
     */
    private String author;
    /**
     * 价格
     */
    private BigDecimal price;
    /**
     * 图片名称
     */
    private String image;
    private static final long serialVersionUID = 1L;
    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        XcxBook other = (XcxBook) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getTitle() == null ? other.getTitle() == null : this.getTitle().equals(other.getTitle()))
            && (this.getAuthor() == null ? other.getAuthor() == null : this.getAuthor().equals(other.getAuthor()))
            && (this.getPrice() == null ? other.getPrice() == null : this.getPrice().equals(other.getPrice()))
            && (this.getImage() == null ? other.getImage() == null : this.getImage().equals(other.getImage()));
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode());
        result = prime * result + ((getAuthor() == null) ? 0 : getAuthor().hashCode());
        result = prime * result + ((getPrice() == null) ? 0 : getPrice().hashCode());
        result = prime * result + ((getImage() == null) ? 0 : getImage().hashCode());
        return result;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", title=").append(title);
        sb.append(", author=").append(author);
        sb.append(", price=").append(price);
        sb.append(", image=").append(image);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ctsi.sddx.cms.respository.product.mapper.ProductMapper">
    <resultMap id="BaseResultMap" type="com.ctsi.sddx.cms.domain.product.entity.ProductBO">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="product_code" property="productCode" jdbcType="VARCHAR"/>
        <result column="product_name" property="productName" jdbcType="CHAR"/>
        <result column="product_model" property="productModel" jdbcType="DATE"/>
        <result column="product_type" property="productType" jdbcType="VARCHAR"/>
        <result column="product_describe" property="productDescribe" jdbcType="VARCHAR"/>
        <result column="product_paymathod" property="productPaymathod" jdbcType="VARCHAR"/>
        <result column="product_payinstructions" property="priductPayinstructions" jdbcType="VARCHAR"/>
        <result column="product_note" property="priductNote" jdbcType="VARCHAR"/>
        <result column="product_shelf" property="productShelf" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="VARCHAR"/>
        <result column="update_time" property="updateTime" jdbcType="VARCHAR"/>
        <result column="product_label" property="productLabel" jdbcType="VARCHAR"/>
        <result column="product_image" property="productImage" jdbcType="VARCHAR"/>
        <result column="product_sort" property="productSort" jdbcType="VARCHAR"/>
        <result column="industry_type" property="industryType" jdbcType="VARCHAR"/>
        <result column="menu_name" property="menuName" jdbcType="VARCHAR"/>
        <result column="is_hot" property="isHot" jdbcType="VARCHAR"/>
    </resultMap>
    <sql id="Base_Column_List">
        p
        .
        *
        ,m.menu_name
    </sql>
    <select id="selectByPrimaryKey" parameterType="com.ctsi.sddx.cms.domain.product.entity.ProductBO"
            resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from cms_product_info p, cms_menu_info m
        where
        p.product_type=m.id
        <if test="productType!=null and productType!=''">
            and p.product_type= #{productType,jdbcType=VARCHAR}
        </if>
        <if test="productCode!=null and productCode!=''">
            and p.product_code= #{productCode,jdbcType=VARCHAR}
        </if>
        <if test="productName!=null and productName!=''">
            and product_name like concat('%',#{productName,jdbcType=VARCHAR},'%')
        </if>
        <if test="industryType!=null and industryType!=''">
            and p.industry_type= #{industryType,jdbcType=VARCHAR}
        </if>
        <if test="productLabel!=null and productLabel!=''">
            and product_label like concat('%',#{productLabel,jdbcType=VARCHAR},'%')
        </if>
        order by p.product_sort desc
    </select>
</mapper>

mapper接口

package com.ctsi.sddx.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.ctsi.sddx.pojo.XcxBook;
/**
 * @Entity com.ctsi.sddx.pojo.XcxBook
 */
@Mapper
public interface XcxBookMapper {
    List<XcxBook> findAllById(@Param("id") Integer id);
    List<XcxBook> findAll();
    List<XcxBook> findAllByTitle(@Param("title") String title);
}

BookController

package com.ctsi.sddx.controller;
import com.ctsi.sddx.mapper.XcxBookMapper;
import com.ctsi.sddx.pojo.XcxBook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
/**
 * @Author : lizzu
 * @create 2022/10/9 11:17
 */
@RestController
@RequestMapping("v1/weChat/")
public class BookController {
    @Resource
    XcxBookMapper xcxBookMapper;
    @GetMapping("/findAllById")
    public List<XcxBook> findAllById (Integer id){
        return xcxBookMapper.findAllById(id);
    }
    @GetMapping("/findAll")
    public List<XcxBook> findAllById (){
        return xcxBookMapper.findAll();
    }
    @GetMapping("/findAllByTitle")
    public List<XcxBook> findAllByTitle (String title){
        return xcxBookMapper.findAllByTitle(title);
    }
}

数据库脚本

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for xcx_book
-- ----------------------------
DROP TABLE IF EXISTS `xcx_book`;
CREATE TABLE `xcx_book`  (
  `id` int(0) NOT NULL COMMENT '编号',
  `title` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图书名称',
  `author` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '作者',
  `price` decimal(10, 2) NULL DEFAULT NULL COMMENT '价格',
  `image` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '图片名称',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of xcx_book
-- ----------------------------
INSERT INTO `xcx_book` VALUES (1, 'java从入门到放弃', '齐XX', 66.66, 'img01.jpg');
INSERT INTO `xcx_book` VALUES (2, 'mysql从删库到跑路', '奇XX', 33.22, 'img02.jpg');
INSERT INTO `xcx_book` VALUES (3, 'Python从入门到捕蛇者说', '齐XX', 22.22, 'img03.jpg');
INSERT INTO `xcx_book` VALUES (4, 'C#从入门到入坟', '齐XX', 11.33, 'img04.jpg');
INSERT INTO `xcx_book` VALUES (5, 'C++从入门到脊椎病康复', '齐XX', 55.33, 'img05.jpg');
INSERT INTO `xcx_book` VALUES (6, 'PHP从看懂到看开', '齐XX', 49.98, 'img06.jpg');
SET FOREIGN_KEY_CHECKS = 1;

测试查询

网络异常,图片无法展示
|

3微信小程序端代码

gitee地址

3.1搜索页面以及静态样式实现

页面:helloworld.wxml

<view>
<view>
<view class="weui-search-bar">
<view class="weui-search-bar__form">
<!-- 搜索框 -->
<view class="weui-search-bar__box">
<icon class="weui-icon-search_in-box" type="search"
size="14"></icon>
<input type="text" class="weui-search-bar__input"
model:value="{{searchContent}}" placeholder="请输入搜索内容"/>
</view>
</view>
<!-- 搜索按钮,调用搜索查询方法 -->
<view class="weui-search-bar__cancel-btn" bindtap='searchBook'>搜索
</view>
</view>
</view>
</view>

样式:helloworld.wxss

/* pages/helloWord/helloWord.wxss */
.weui-search-bar {
  position: relative;
  padding: 8px 10px;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  box-sizing: border-box;
  background-color: #EFEFF4;
  border-top: 1rpx solid #D7D6DC;
  border-bottom: 1rpx solid #D7D6DC;
  }
  .weui-icon-search_in-box {
  position: absolute;
  left: 10px;
  top: 7px;
  }
  .weui-search-bar__form {
  position: relative;
  -webkit-box-flex: 1;
  -webkit-flex: auto;
  flex: auto;
  border-radius: 5px;
  background: #FFFFFF;
  border: 1rpx solid #E6E6EA;
  }
  .weui-search-bar__box {
  position: relative;
  padding-left: 30px;
  padding-right: 30px;
  width: 100%;
  box-sizing: border-box;
  z-index: 1;
  }
  .weui-search-bar__input {
  height: 28px;
  line-height: 28px;
  font-size: 14px;
  }
  .weui-search-bar__cancel-btn {
  margin-left: 10px;
  line-height: 28px;
  color: #09BB07;
  white-space: nowrap;
  }

效果

网络异常,图片无法展示
|

静态图书列表页面

<view>
  <view>
    <view class="weui-search-bar">
      <view class="weui-search-bar__form">
        <!-- 搜索框 -->
        <view class="weui-search-bar__box">
          <icon class="weui-icon-search_in-box" type="search" size="14"></icon>
          <input type="text" class="weui-search-bar__input" model:value="{{searchContent}}" placeholder="请输入搜索内容" />
        </view>
      </view>
      <!-- 搜索按钮,调用搜索查询方法 -->
      <view class="weui-search-bar__cancel-btn" bindtap='searchBook'>搜索
      </view>
    </view>
  </view>
</view>
<view class="book">
  <view class="book-left">
    <image src="/imgs/img01.jpg" alt="" />
  </view>
  <view class="book-right">
    <view id="title">Java从入门到放弃(第五版)</view>
    <view id="author">今日科技</view>
    <view id="price">¥ 47.50</view>
  </view>
</view>
<view class="book">
  <view class="book-left">
    <image src="/imgs/img02.jpg" alt="" />
  </view>
  <view class="book-right">
    <view id="title">mysql从删库到跑路</view>
    <view id="author">今日科技</view>
    <view id="price">¥ 52.10</view>
  </view>
</view>
<view class="book">
  <view class="book-left">
    <image src="/imgs/img03.jpg" alt="" />
  </view>
  <view class="book-right">
    <view id="title">Python从入门到入狱(第四版)</view>
    <view id="author">Bruce Eckel</view>
    <view id="price">¥ 70.20</view>
  </view>
</view>
<view class="book">
  <view class="book-left">
    <image src="/imgs/img04.jpg" alt="" />
  </view>
  <view class="book-right">
    <view id="title">C#从入门到入坟 精粹版</view>
    <view id="author">今日科技</view>
    <view id="price">¥ 63.00</view>
  </view>
</view>
<view class="book">
  <view class="book-left">
    <image src="/imgs/img05.jpg" alt="" />
  </view>
  <view class="book-right">
    <view id="title">C++从入门到脊椎病康复</view>
    <view id="author">今日科技</view>
    <view id="price">¥ 99.00</view>
  </view>
</view>
<view class="book">
  <view class="book-left">
    <image src="/imgs/img06.jpg" alt="" />
  </view>
  <view class="book-right">
    <view id="title">PHP从看懂到看开</view>
    <view id="author">今日科技</view>
    <view id="price">¥ 99.00</view>
  </view>
</view>

效果

网络异常,图片无法展示
|

3.2通过后端接口获取数据

helloWord.js

/**
   * 页面的初始数据
   */
  data: {
    searchContent: "",
    bookList: null
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.searchBook();
  },
  searchBook(e) {
    console.log(this.data.searchContent);
    var title = this.data.searchContent;
    var that = this;
    // 重置数据 
    that.setData({
      bookList: null
    }) 
    wx.request({
      url: 'https://6016a95m81.zicp.fun/v1/weChat/findAllByTitle',
      method: "GET",
      data: {
        title: title
      },
      header: {
        'content-type': 'application/json' // 默认值 
      },
      success(res) {
        console.log(res.data);
        var bookList = res.data;
        console.log(that) 
        that.setData({
          bookList: bookList
        })
      }
    })
  },

页面修改 通过wx:for遍历bookList

<view class="book" wx:for="{{bookList}}">
  <view class="book-left">
    <image src="/imgs/{{item.image}}" alt="" />
  </view>
  <view class="book-right">
    <view id="title">{{item.title}}</view>
    <view id="author">{{item.author}}</view>
    <view id="price">¥ {{item.price}}</view>
  </view>
</view>

测试

网络异常,图片无法展示
|

模糊搜索

网络异常,图片无法展示
|

下一篇:

微信小程序电商实战
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
20天前
|
算法 JavaScript 前端开发
切西瓜法实现微信抢红包功能
该文章介绍了使用“切西瓜法”和“栅栏法”两种算法来模拟微信抢红包的随机分配机制,并通过具体的JavaScript代码实现了红包金额的公平随机分配过程。
切西瓜法实现微信抢红包功能
|
1月前
|
人工智能 前端开发 JavaScript
MacTalk 测评通义灵码,实现“微信表情”小功能
墨问西东创始人池建强分享了团队使用通义灵码的经验。
|
1月前
|
小程序 API 开发工具
使用python 实现微信签到提醒功能
【9月更文挑战第4天】使用python 实现微信签到提醒功能
57 2
|
2月前
|
Web App开发 缓存 小程序
【Azure API 管理】从微信小程序访问APIM出现200空响应的问题中发现CORS的属性[terminate-unmatched-request]功能
【Azure API 管理】从微信小程序访问APIM出现200空响应的问题中发现CORS的属性[terminate-unmatched-request]功能
|
3天前
|
小程序 API
微信小程序更新提醒uniapp
在小程序开发中,版本更新至关重要。本方案利用 `uni-app` 的 `uni.getUpdateManager()` API 在启动时检测版本更新,提示用户并提供立即更新选项,自动下载更新内容,并在更新完成后重启小程序以应用新版本。适用于微信小程序,确保用户始终使用最新版本。以下是实现步骤: ### 实现步骤 1. **创建更新方法**:在 `App.vue` 中创建 `updateApp` 方法用于检查小程序是否有新版本。 2. **测试**:添加编译模式并选择成功状态进行模拟测试。
10 0
微信小程序更新提醒uniapp
|
2月前
|
小程序 前端开发 Java
SpringBoot+uniapp+uview打造H5+小程序+APP入门学习的聊天小项目
JavaDog Chat v1.0.0 是一款基于 SpringBoot、MybatisPlus 和 uniapp 的简易聊天软件,兼容 H5、小程序和 APP,提供丰富的注释和简洁代码,适合初学者。主要功能包括登录注册、消息发送、好友管理及群组交流。
79 0
SpringBoot+uniapp+uview打造H5+小程序+APP入门学习的聊天小项目
|
2月前
|
小程序 前端开发 JavaScript
【项目实战】SpringBoot+uniapp+uview2打造一个企业黑红名单吐槽小程序
【避坑宝】是一款企业黑红名单吐槽小程序,旨在帮助打工人群体辨别企业优劣。该平台采用SpringBoot+MybatisPlus+uniapp+uview2等技术栈构建,具备丰富的注释与简洁的代码结构,非常适合实战练习与学习。通过小程序搜索“避坑宝”即可体验。
76 0
【项目实战】SpringBoot+uniapp+uview2打造一个企业黑红名单吐槽小程序
|
2月前
|
存储 小程序 JavaScript
|
2月前
|
小程序 前端开发 安全
|
3月前
|
JavaScript Java 测试技术
基于SpringBoot+Vue+uniapp的汉服交易小程序的详细设计和实现(源码+lw+部署文档+讲解等)
基于SpringBoot+Vue+uniapp的汉服交易小程序的详细设计和实现(源码+lw+部署文档+讲解等)
48 7

热门文章

最新文章