Practicing WeChat Mini Programs: Front-end + Back-end (Java)

Click on the blue font above and select "Star Official Account"

High-quality articles, delivered immediately

Follow the official account backstage to reply to pay or mall to obtain actual project information + video

Author: BingeZha

csdn.net/zwb19940216/article/details/81023191

1 Introduction

Nowadays, WeChat Mini Programs are getting more and more popular. I believe that many people have learned WeChat Mini Programs or tried to develop them through various ways. The author has developed WeChat Mini Programs because of his interest in understanding. In the end, his graduation project is also to develop a WeChat Mini Program. program. So now use this blog to record some of my previous development experience and some insights.

2. Main content

  • Springboot back-end architecture construction

  • Small program project construction

  • Mini program api call

  • Background resetful interface writing

  • The applet calls the background interface

  • Free https application

  • linux sub-department line

3. WeChat Mini Program Project Construction

I will not introduce these basic things too much. When you first started development, you generally did not have your own server and domain name, so when you write locally, you will "not verify" in the "Project Settings" under "Details". Domain name security" is checked.

Write picture description here

As for the components of the WeChat applet, that is, the development of the front-end page, I hope you can resist loneliness and earnestly work on the WeChat development platform.

Component

https://developers.weixin.qq.com/miniprogram/dev/component/

api:

https://developers.weixin.qq.com/miniprogram/dev/api/

4. Detailed back-end

I write in the back-end mainly in java. Of course, those who are familiar with other development languages ​​can also use other languages ​​to develop the back-end. Now I will write the explanation of the back-end api in java. The main framework is springboot, the development tool myeclipse, and the server Alibaba Cloud server.

Create a maven project and import related dependencies:

pom.xml dependency

<!-- 统一版本控制 -->
<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
 <!-- freemarker渲染页面 -->
 <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker -->
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
 </dependency>

 <!-- spring boot 核心 -->
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

 <!-- springboot整合jsp -->
 <!-- tomcat 的支持. -->
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
   <exclusion>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
   </exclusion>
  </exclusions>
 </dependency>

 <dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-jasper</artifactId>
 </dependency>
</dependencies>

You can modify some configuration parameters by creating an application.properties file under the configuration file src/main/resources/.

#jsp支持
spring.mvc.view.suffix=.jsp
spring.mvc.view.prefix=/WEB-INF/jsp/
#this is set port
#server.port=80
server.port=443
#添加ssl证书
#ssl证书文件名
server.ssl.key-store=classpath:xxxxxxx.pfx
server.ssl.key-store-password=xxxxxxxx
server.ssl.keyStoreType=xxxxxxxx

In the actual project, the database may be involved, and mybatis must be integrated. In the article, I just do the test and will not do the test using the database.

First create the entry program of springboot: paste the code below app.class:

@ComponentScan(basePackages= "com.bin")//添加扫包@ComponentScan(basePackages= "")
@EnableAutoConfiguration
public class App{

 //启动springboot
 public static void main(String[] args) {
  SpringApplication.run(App.class, args);
 }
}

Right-click run when starting the project.

When writing a test controller to communicate with the WeChat applet and java back-end, the controller code is as follows:

@RestController
@SpringBootApplication
public class ControllerText {
 
 @RequestMapping("getUser")
 public Map<String, Object> getUser(){
  System.out.println("微信小程序正在调用。。。");
  Map<String, Object> map = new HashMap<String, Object>();
  List<String> list = new ArrayList<String>();
   list.add("zhangsan");
   list.add("lisi");
   list.add("wanger");
   list.add("mazi");
   map.put("list",list);
  System.out.println("微信小程序调用完成。。。");
  return map;
 }
 
 @RequestMapping("getWord")
 public Map<String, Object> getText(String word){
  Map<String, Object> map = new HashMap<String, Object>();
  String message = "我能力有限,不要为难我";
  if ("后来".equals(word)) {
   message="正在热映的后来的我们是刘若英的处女作。";
  }else if("微信小程序".equals(word)){
   message= "想获取更多微信小程序相关知识,请更多的阅读微信官方文档,还有其他更多微信开发相关的内容,学无止境。";
  }else if("西安工业大学".equals(word)){
   message="西安工业大学(Xi'an Technological University)简称”西安工大“,位于世界历史名城古都西安,是中国西北地区唯一一所以兵工为特色,以工为主,理、文、经、管、法协调发展的教学研究型大学。原中华人民共和国兵器工业部直属的七所本科院校之一(“兵工七子”),陕西省重点建设的高水平教学研究型大学、陕西省人民政府与中国兵器工业集团、国防科技工业局共建高校、教育部“卓越工程师教育培养计划”试点高校、陕西省大学生创新能力培养综合改革试点学校。国家二级保密资格单位,是一所以\"军民结合,寓军于民\"的国防科研高校。";
  }
  map.put("message", message);
  return map;
 }
 
 @RequestMapping("")
 public String getText(){
  return "hello world";
 }

}

So far, the simple back-end framework and testing are basically completed.

Note: The difference between @RestController and @Controller annotation @RestController is equivalent to two annotations, which can realize the data obtained from the back end in the form of json string in the front-end page (web page). The data transfer between the WeChat applet and the background is in the form of json messages. So this is one of the main reasons for choosing the springboot framework to develop the backend of small programs. It can facilitate our back-end development of small programs.

5. The Mini Program initiates a network request

After completing the back-end development of the small program, the next step is to initiate a network request on the small program side.

Let's take a simple button request data as an example:

wxml file

<button bindtap='houduanButton1'>点击发起请求</button>
<view wx:for="{
    
    {list}}">
    姓名:{
    
    {item}}
  </view>

js file

 /**
   * 页面的初始数据
   */
  data: {
    list: '',
    word: '',
    message:''

  },
  houduanButton1: function () {
    var that = this;
    wx.request({
      url: 'http://localhost:443/getUser',
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)//打印到控制台
        var list = res.data.list;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            list: list
          })
        }
      }
    })
  }

The main api called is wx.request. If you want to know the detailed introduction, you can go to the WeChat public platform.

Next, take the search type request as an example:

wxml file:

 <input type="text" class="houduanTab_input" placeholder="请输入你要查询的内容" bindinput='houduanTab_input'></input>
  <button bindtap='houduanButton2'>查询</button>
  <view wx:if="{
    
    {message!=''}}">
    {
    
    {message}}
  </view>

js file: see the previous js file for the definition of variables

//获取输入框的内容
  houduanTab_input: function (e) {
    this.setData({
      word: e.detail.value
    })
  },
  // houduanButton2的网络请求
  houduanButton2: function () {
    var that = this;
    wx.request({
      url: 'http://localhost:443/getWord',
      data:{
        word: that.data.word
      },
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)//打印到控制台
        var message = res.data.message;
        if (message == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: toastText,
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            message: message
          })
        }
      }
    })
  }

So far, a simple WeChat applet terminal to communicate with the java backend has been completed.

Now you can start the back-end project to test on the WeChat development tool.

Demonstration effect:

Write picture description here

So so far, the front-end and back-end communication of the applet has been completed.

6. https application

In fact, it's not really an application. You can apply for a free SSL certificate after purchasing the domain name. There is the certificate configuration in the previous configuration file application.properties, and the pfx file of the certificate can be directly added to the back-end project.

7. Purchase server to deploy back-end api code

For the springboot project, I suggest to type the jar and deploy it directly on the server. You only need to install the corresponding version of jdk on the server. Project deployment command:

I purchased a lightweight application server deployed by Alibaba Cloud. More cost-effective.

Run the command:

 nohup java -jar helloworld.jar &

Nohup means not to hang the service. It means to be resident. Unless the cloud server is restarted, it will not work; the last & means that the log file nohup.out will be generated after executing the command.

Of course you can also use java -jar helloworld.jar

Source code:

Link: https://pan.baidu.com/s/1PfByFfEgqkVALcc3PRhn9w Extraction code: c7yf




有热门推荐????
新垣结衣发新片了!MySQL 怎么优化才能扛住?又一神操作,SpringBoot2.x 集成百度 uidgenerator搞定全局ID为什么阿里不允许用Executors创建线程池,而是通过ThreadPoolExecutor的方式?
为什么要在2021年放弃Jenkins?我已经对他失去耐心了...
Docker + FastDFS + Spring Boot 一键式搭建分布式文件服务器面试官:这货一听就是一个水货...2020年度开发者工具Top 100名单!我怎么99%的都没用过,是我太low?

点击阅读原文,前往学习SpringCloud实战项目

Guess you like

Origin blog.csdn.net/qq_17231297/article/details/114650587