微信小程序练手实战:前端+后端(Java)
1. 主要内容
springboot后端架构构建 小程序项目构建 小程序api调用 后台resetful接口编写 小程序调用后台接口 免费的https申请 linux下部署上线
3. 后端详解
这里在后端编写主要是用java,当然对其他开发语言熟悉的也可以使用其他语言开发后端。现在我就java编写后端api的讲解。主要框架springboot,开发工具myeclipse,服务器阿里云服务器。创建一个maven项目,导入相关依赖:pom.xml依赖
<!-- 统一版本控制
--><parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>1.5.9.RELEASE</parent><dependencies><!-- freemarker渲染页面 -->
在配置文件src/main/resources/下创建application.properties文件可以修改一些配置参数等。
#jsp支持spring.mvc.view.suffix=.jspspring.mvc.view.prefix=/WEB-INF/jsp/#this is set port#server.port=80server.port=443#添加ssl证书#ssl证书文件名server.ssl.key-store=classpath:xxxxxxx.pfxserver.ssl.key-store-password=xxxxxxxxserver.ssl.keyStoreType=xxxxxxxx
在实际项目中可能涉及数据库,还要整合mybatis,在文章中,我仅仅做测试就不做使用数据库的测试。首先创建springboot的入口程序:app.class下面贴上代码:
@ComponentScan(basePackages="com.bin")//添加扫包@ComponentScan(basePackages= "")@EnableAutoConfigurationpublicclassApp{//启动springbootpublicstaticvoidmain(String[] args){ SpringApplication.run(App.class, args); }}
"; }map.put("message", message);returnmap; }@RequestMapping("")publicStringgetText(){return"hello world"; }}
4. 小程序发起网络请求
在完成了小程序的后端开发,下面进行小程序端发起网络请求。下面以一个简单的按钮请求数据为例:wxml文件
点击发起请求姓名:{ {item}}</view>
js文件
/** * 页面的初始数据 */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)//打印到控制台varlist= res.data.list;if(list== null) {var toastText =数据获取失败; wx.showToast({ title: toastText,icon:, duration: 2000 }); } else { that.setData({ list: list }) } } })}
wxml文件:
查询{ {message}}</view>
js文件:变量的定义见上一个js文件
//获取输入框的内容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 }) } } })}
所以至此已经完成了小程序的前后端通信。
5. https申请
其实也不算什么申请,在购买域名之后可以申请免费的ssl证书,在前面的配置文件application.properties中有证书的配置,将证书的pfx文件直接添加到后端项目下即可
6. 购买服务器部署后端api代码
对于springboot项目,建议打jar,直接在服务器上部署即可,在服务器上只需要安装对应版本的jdk即可。项目部署命令:我购买的是阿里云的轻量级应用服务器部署的。比较划算吧。
运行命令:nohup java -jar helloworld.jar &
nohup的意思不挂服务,常驻的意思,除非云服务器重启,那就没法了;最后一个&表示执行命令后要生成日志文件nohup.out。当然还可以使用java -jar helloworld.jar
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系小编,我们将立即处理