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

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 微信小程序实战 (微信小程序实现图书查询功能)

上一篇简单的写了个微信小程序调用后端接口的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>

测试

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

模糊搜索

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

下一篇:

微信小程序电商实战
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
8天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的微信课堂助手小程序的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的微信课堂助手小程序的详细设计和实现
39 3
|
8天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的微信阅读网站小程序的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的微信阅读网站小程序的详细设计和实现
37 2
|
8天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的健身管理系统及会员微信小程序的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的健身管理系统及会员微信小程序的详细设计和实现
29 0
|
8天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的微信阅读小程序的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的微信阅读小程序的详细设计和实现
28 0
|
8天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的旅游出行必备商城小程序的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的旅游出行必备商城小程序的详细设计和实现
29 0
|
15天前
|
小程序 前端开发 API
微信小程序全栈开发中的异常处理与日志记录
【4月更文挑战第12天】本文探讨了微信小程序全栈开发中的异常处理和日志记录,强调其对确保应用稳定性和用户体验的重要性。异常处理涵盖前端(网络、页面跳转、用户输入、逻辑异常)和后端(数据库、API、业务逻辑)方面;日志记录则关注关键操作和异常情况的追踪。实践中,前端可利用try-catch处理异常,后端借助日志框架记录异常,同时采用集中式日志管理工具提升分析效率。开发者应注意安全性、性能和团队协作,以优化异常处理与日志记录流程。
|
15天前
|
小程序 安全 数据安全/隐私保护
微信小程序全栈开发中的身份认证与授权机制
【4月更文挑战第12天】本文探讨了微信小程序全栈开发中的身份认证与授权机制。身份认证包括手机号验证、微信登录和第三方登录,而授权机制涉及角色权限控制、ACL和OAuth 2.0。实践中,开发者可利用微信登录获取用户信息,集成第三方登录,以及实施角色和ACL进行权限控制。注意点包括安全性、用户体验和合规性,以保障小程序的安全运行和良好体验。通过这些方法,开发者能有效掌握小程序全栈开发技术。
|
15天前
|
JavaScript 前端开发 小程序
微信小程序全栈开发之性能优化策略
【4月更文挑战第12天】本文探讨了微信小程序全栈开发的性能优化策略,包括前端的资源和渲染优化,如图片压缩、虚拟DOM、代码分割;后端的数据库和API优化,如索引创建、缓存使用、RESTful API设计;以及服务器的负载均衡和CDN加速。通过这些方法,开发者可提升小程序性能,优化用户体验,增强商业价值。
|
15天前
|
小程序 前端开发 JavaScript
微信小程序全栈开发中的PWA技术应用
【4月更文挑战第12天】本文探讨了微信小程序全栈开发中PWA技术的应用,PWA结合Web的开放性和原生应用的性能,提供离线访问、后台运行、桌面图标和原生体验。开发者可利用Service Worker实现离线访问,Worker处理后台运行,Web App Manifest添加桌面图标,CSS和JavaScript提升原生体验。实践中需注意兼容性、性能优化和用户体验。PWA技术能提升小程序的性能和用户体验,助力开发者打造优质小程序。
|
1月前
|
小程序 前端开发 程序员
微信小程序开发入门教程-小程序账号注册及开通
微信小程序开发入门教程-小程序账号注册及开通