SSM框架实现微信小程序前后端数据通信样例项目(附完整的项目样例工程源码)

  • 因为最近的项目需要,简单提供一个微信小程序与Java后端进行数据交互的项目模板,同时也建立了网页WEB的测试,方便搭建pc端后台管理界面。因为有些内容网上也比较多,部分环境安装和项目创建内容不加强调。下面进入主题吧:

1、使用工具:
(1)微信小程序开发者工具
(2)IDEA
(3)SSM框架
(4)MySQL数据库

2.微信小程序前端框架
这个就不多介绍了,下载安装好开发环境,建立项目,会自动创建一个框架模板。

建立模板以及底部导航栏:https://study.163.com/course/introduction.htm?
微信小程序基础入门学习视频:
courseId=1003283028&trace_c_p_k2=20f6fbe78e844135a0f53a349830a6d2

3.SSM框架搭建
(1)创建项目,选择创建Maven项目,选择其中的webapp模板,这个也不在累赘,可搜索相关博客如何创建一个Maven管理的Java Web项目模板。

参考博客: https://blog.csdn.net/zonghengxueba/article/details/80829195

(2)框架相关配置文件设立
首先本项目的后端目录结构如下:
SSM框架实现微信小程序前后端数据通信样例项目(附完整的项目样例工程源码)_第1张图片
3.1 Java文件模板建立
(1)配置pom.xml文件
特别需要注意一下数据库的版本以及一些项目工程信息可能需要改成你的工程名字,本项目名称为:Minqingtong_System

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>Minqingtong_System</groupId>
  <artifactId>Minqingtong_System</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Minqingtong_System Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <!-- spring版本号 -->
    <spring.version>4.3.5.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.4.1</mybatis.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/jstl/jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/taglibs/standard -->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!--日志 start-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <!--日志 end-->

    <!-- 实现slf4j接口并整合 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- JSON -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.8.7</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.7</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.8.7</version>
    </dependency>

    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.3</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>

    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.2.3</version>
      <classifier>jdk15</classifier>
    </dependency>

    <!-- 数据库 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.13</version>
    </dependency>

    <!-- 数据库连接池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <!-- mybatis/spring整合包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.websocket</groupId>
      <artifactId>javax.websocket-api</artifactId>
      <version>1.1</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-websocket</artifactId>
      <version>4.0.5.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-messaging</artifactId>
      <version>4.0.5.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>Minqingtong_System</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

(2)配置web.xml文件
如果有标红报错的地方,先不管,等创建好相应的文件后,回过来看是否是文件名不一致。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

  <context-param>
    <!--加载Spring的配置文件,随着监听器触发,Spring调用这里,找到Spring的核心配置文件-->
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:config/spring-mybatis.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--当页面有请求时,DispatcherServlet对象调用这里,获取到SpringMVC的核心配置文件-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:config/Spring-mvc.xml</param-value>
    </init-param>
    <!--优先级,数字越小级别越高-->
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>

  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!--解决字符编码异常的过滤器-->
  <filter>
    <filter-name>EncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceRequestEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*
  

  Archetype Created Web Application

(3)配置Spring-mvc.xml文件
文件目录:resources/config/

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--将链接中/p的静态的访问路径映射为URL,常用于加载html、js、css、图片、视频等静态资源-->
    <!--<mvc:resources mapping="/resources/**" location="/,classpath:/META-INF/publicResources/"/>-->
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/lib/" mapping="/lib/**" />
    <!--使用注解(可以代替配置映射器和适配器)-->
    <mvc:annotation-driven/>
    <!--扫描带有注解的控制类,不可以放在Spring的配置中-->
    <context:component-scan base-package="com.MinQingTong.Controller"/>
    <!-- 视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

(4)配置spring-mybatis.xml文件
文件目录:resources/config/

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.MinQingTong.Service.Impl"/>

    <!-- 配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:properties/jdbc.properties"/>
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
    </bean>
    <!-- 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描mapping.xml文件,**表示迭代查找 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>
    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.MinQingTong.Dao"/>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

(5)配置jabc.properties文件
文件目录:resources/properties/,并改成你的数据库名称和数据库用户名、密码。

jdbc.driver=com.mysql.cj.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/minqingtong_system?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
#用户名
jdbc.username=root
#密码
jdbc.password=password
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2

(6)配置log4j.properties文件
文件目录:resources/properties/,

### set log levels ###
log4j.rootLogger = DEBUG,Console,File
###  输出到控制台  ###
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= %d{ABSOLUTE} %5p %c{1}:%L - %m%n

(7)Java类和接口文件配置(测试代码)
Controller模块:创建TestController类

@Controller
@RequestMapping("/test")
public class TestController {
    @Autowired
    private TestService testService;
    /**
     * pc管理后台数据测试
     * @return
     */
    @RequestMapping(value = "/user")
    @ResponseBody
    public List<Test> getTest(){
        List<Test> user = testService.test();
        System.out.print("测试数据输出:id:"+user);
        return user;
    }
    /**
     * 微信小程序数据测试
     * @return
     */
    @RequestMapping(value="/xiaochenxu/getUser")
    @ResponseBody
    public List<Test> getUser(){
        List<Test> user = testService.test();
        System.out.print("测试数据输出:id:"+user);
        return user;
    }
}

Dao模块:创建TestMapper接口

package com.MinQingTong.Dao;
import com.MinQingTong.Model.Test;
import java.util.List;
public interface TestMapper {
    /**
     * 数据测试
     * @return
     */
    List<Test> test();
}

Model模块:创建Test实体类

package com.MinQingTong.Model;
public class Test {
    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Test{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

Service模块:创建TestService接口和实现类

package com.MinQingTong.Service;
import com.MinQingTong.Model.Test;
import java.util.List;
public interface TestService {
    /**
     * 数据测试
     * @return
     */
    List<Test> test();
}

实现类:

package com.MinQingTong.Service.Impl;
import com.MinQingTong.Dao.TestMapper;
import com.MinQingTong.Model.Test;
import com.MinQingTong.Service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private TestMapper testMapper;
    /**
     * 数据测试
     * @return
     */
    @Override
    public List<Test> test(){
        return testMapper.test();
    }
}

数据库mapper模块:
目录:resources/mapper/,创建TestMapper.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.MinQingTong.Dao.TestMapper">
    <resultMap id="user" type="com.MinQingTong.Model.Test">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
    </resultMap>
    <select id="test" resultMap="user">
        select id,name from test
    </select>
</mapper>

pc管理后台界面:
打开index.jsp,写入测试代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>测试</title>
    <c:set var="path" value="${pageContext.request.contextPath}" scope="page"/>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
    <h2>PC后台数据测试!</h2>
    <div>
        <div>
            用户ID:<span id="id">
        </div>
        <div>
            用户名:<span id="name"></span>
        </div>
    </div>
</body>
<script type="text/javascript" src="${path}/lib/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        $.ajax({
            url : "${path}/test/user",
            type : "post",
            async: true,
            success : function(result){
                $("#id").html(result[0].id);
                $("#name").html(result[0].name);
            }
        })
    })
</script>
</html>

4.数据库建立
建立数据库以及数据表,表明可为test,建立两个测试字段:id和name。

5.微信小程序关键代码.
.wxml文件:

<!--后台接入数据测试-->
<button bindtap='houduanRequest'>点击进行后台数据测试</button>
<view wx:for="{{list}}" wx:fot-item="item">
  用户ID{{item.id}}
  用户名:{{item.name}}
</view>

.js文件:
SSM框架实现微信小程序前后端数据通信样例项目(附完整的项目样例工程源码)_第2张图片
5.运行代码
(1)配置好tomcat后,运行后端代码,会弹出一个测试网页,数据显示成功即可;
(2)打开微信前端代码,点击测试是否获得数据,若出现提示端口不允许,及url链接无法认证,需在开发者工具中进行设置:
解决办法:
在请求本地接口时,要开启"不校验请求域名、TLS版本及HTTPS证书"选项:设置->项目设置->不校验请求域名、TLS版本及HTTPS证书。因为wx.request的url请求中不能有端口。

遇到该问题可以参考博客: https://www.cnblogs.com/zeroingToOne/p/8987554.html

在这里插入图片描述
SSM框架实现微信小程序前后端数据通信样例项目(附完整的项目样例工程源码)_第3张图片
至此一个简单的微信小程序与java后台通信的项目Demo搭建测试完成!其间如果遇到各种报错问题多百度,博主也是这样做的。
同时IDEA有个功能特别强大,就是如果出现运行tomcat项目报错了,可以查看调试代码工具底下的Tomcat服务日志快速定位到哪里出错了。

注明:下一篇博文将介绍这类项目在阿里云服务器上的部署过程,以及小程序的发布过程。

工程源码下载链接:
https://download.csdn.net/download/qq_28406091/12185128

你可能感兴趣的:(项目)