一、前言

现在微信小程序越来越火了,相信不少人都通过各种途径学习过微信小程序或者尝试开发,作者就是曾经由于兴趣了解开发过微信小程序,所以现在用这篇博客记录我之前开发的一些经验和一些心得吧。

二、主要内容
  1. Springboot后端架构构建
  2. 小程序项目构建
  3. 小程序api调用
  4. 后台resetful接口编写
  5. 小程序调用后台接口
  6. 免费的https申请
  7. linux下部署上线
三、微信小程序项目构建

这些基础的东西我就不过多介绍,大家在刚开始开发的时候一般都没有自己的服务器及域名,所以大家在本地编写的时候,在“详细”下的“项目设置”里面将“不校验域名安全性”勾选。

微信小程序后端开发详细步骤(微信小程序开发)(1)

至于微信小程序的组件,即前端页面的开发希望大家耐住寂寞认真在微信开发平台上。

组件:

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

api:

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

四、后端详解

我在后端编写主要是用Java,当然对其他开发语言熟悉的也可以使用其他语言开发后端。现在我就java编写后端api的讲解。主要框架springboot,开发工具myeclipse,服务器阿里云服务器。

创建一个Maven项目,导入相关依赖:

pom.xml依赖

<!-- 统一版本控制 --> <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>

在配置文件src/main/resources/下创建application.properties文件可以修改一些配置参数等。

#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

在实际项目中可能涉及数据库,还要整合mybatis,在文章中,我仅仅做测试就不做使用数据库的测试。

首先创建springboot的入口程序:app.class下面贴上代码:

@ComponentScan(basePackages= "com.bin")//添加扫包@ComponentScan(basePackages= "") @EnableAutoConfiguration public class App{ //启动springboot public static void main(String[] args) { SpringApplication.run(App.class, args); } }

启动项目时直接右击run即可。

在写一个测试的controller进行微信小程序与java后端实现通信,controller代码如下:

@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"; } }

至此简易的后端框架及测试基本完成。

说明:@RestController与@Controller注解的区别@RestController相当于两个注解,它能实现将后端得到的数据在前端页面(网页)中以json串的形式传递。而微信小程序与后台之间的数据传递就是以json报文的形式传递。所以这就是选择springboot框架开发小程序后端的主要原因之一。可以方面我们进行小程序的后端开发。

五、小程序发起网络请求

在完成了小程序的后端开发,下面进行小程序端发起网络请求。

下面以一个简单的按钮请求数据为例:

wxml文件

<button bindtap='houduanButton1'>点击发起请求</button> <view wx:for="{{list}}"> 姓名:{{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)//打印到控制台 var list = res.data.list; if (list == null) { var toastText = '数据获取失败'; wx.showToast({ title: toastText, icon: '', duration: 2000 }); } else { that.setData({ list: list }) } } }) }

主要调用的api就是wx.request,想知道将详细的介绍大家可以去微信公众平台(https://developers.weixin.qq.com/miniprogram/dev/api/)。

接下来以搜索类型的请求为例:

wxml文件:

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

至此已经完成了简易的微信小程序端与java后端进行通信。

现在可以在启动后端项目在微信开发工具上进行测试。

演示效果:

微信小程序后端开发详细步骤(微信小程序开发)(2)

微信小程序后端开发详细步骤(微信小程序开发)(3)

所以至此已经完成了小程序的前后端通信。

六、ps申请

其实也不算什么申请,在购买域名之后可以申请免费的ssl证书,在前面的配置文件application.properties中有证书的配置,将证书的pfx文件直接添加到后端项目下即可。

七、购买服务器部署后端api代码

对于springboot项目,本人建议打jar,直接在服务器上部署即可,在服务器上只需要安装对应版本的jdk即可。项目部署命令:

我购买的是阿里云的轻量级应用服务器部署的。比较划算吧。

运行命令: nohup java -jar helloworld.jar &

nohup的意思不挂服务,常驻的意思,除非云服务器重启,那就没法了;最后一个&表示执行命令后要生成日志文件nohup.out,当然还可以使用java -jar helloworld.jar。

Redis字符串的实现

Redis虽然是用C语言写的,但却没有直接用C语言的字符串,而是自己实现了一套字符串。目的就是为了提升速度,提升性能,可以看出Redis为了高性能也是煞费苦心。

Redis构建了一个叫做简单动态字符串(Simple Dynamic String),简称SDS

1.SDS 代码结构

struct sdshdr{ // 记录已使用长度 int len; // 记录空闲未使用的长度 int free; // 字符数组 char[] buf; };

SDS ?什么鬼?可能对此陌生的朋友对这个名称有疑惑。只是个名词而已不必在意,我们要重点欣赏借鉴Redis的设计思路。下面画个图来说明,一目了然。

微信小程序后端开发详细步骤(微信小程序开发)(4)

Redis的字符串也会遵守C语言的字符串的实现规则,即最后一个字符为空字符。然而这个空字符不会被计算在len里头。

2.SDS 动态扩展特点

SDS的最厉害最奇妙之处在于它的Dynamic。动态变化长度。举个例子

微信小程序后端开发详细步骤(微信小程序开发)(5)

如上图所示刚开始s1 只有5个空闲位子,后面需要追加' world' 6个字符,很明显是不够的。那咋办?Redis会做以下三个操作:

  1. 计算出大小是否足够
  2. 开辟空间至满足所需大小
  3. 开辟与已使用大小len相同长度的空闲free空间(如果len < 1M)开辟1M长度的空闲free空间(如果len >= 1M)

看到这儿为止有没有朋友觉得这个实现跟Java的列表List实现有点类似呢?看完后面的会觉得更像了。Spring面试题分享

概述

对于 Spring和 SpringBoot到底有什么区别,我听到了很多答案,刚开始迈入学习 SpringBoot的我当时也是一头雾水,随着经验的积累、我慢慢理解了这两个框架到底有什么区别,相信对于用了 SpringBoot很久的同学来说,还不是很理解 SpringBoot到底和 Spring有什么区别,看完文章中的比较,或许你有了不同的答案和看法!

什么是Spring

作为 Java开发人员,大家都 Spring都不陌生,简而言之, Spring框架为开发 Java应用程序提供了全面的基础架构支持。它包含一些很好的功能,如依赖注入和开箱即用的模块,如:

SpringJDBC、SpringMVC、SpringSecurity、SpringAOP、SpringORM、SpringTest,这些模块缩短应用程序的开发时间,提高了应用开发的效率例如,在 JavaWeb开发的早期阶段,我们需要编写大量的代码来将记录插入到数据库中。但是通过使用 SpringJDBC模块的 JDBCTemplate,我们可以将操作简化为几行代码。

什么是Spring Boot

SpringBoot基本上是 Spring框架的扩展,它消除了设置 Spring应用程序所需的 XML配置,为更快,更高效的开发生态系统铺平了道路。

SpringBoot中的一些特征:

1、创建独立的 Spring应用。2、嵌入式 Tomcat、 Jetty、 Undertow容器(无需部署war文件)。3、提供的 starters 简化构建配置4、尽可能自动配置 spring应用。5、提供生产指标,例如指标、健壮检查和外部化配置6、完全没有代码生成和 XML配置要求

从配置分析Maven依赖

首先,让我们看一下使用Spring创建Web应用程序所需的最小依赖项

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.0.RELEASE</version> </dependency>

与Spring不同,Spring Boot只需要一个依赖项来启动和运行Web应用程序:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.0.6.RELEASE</version> </dependency>

在进行构建期间,所有其他依赖项将自动添加到项目中。

另一个很好的例子就是测试库。我们通常使用 SpringTest, JUnit, Hamcrest和 Mockito库。在 Spring项目中,我们应该将所有这些库添加为依赖项。但是在 SpringBoot中,我们只需要添加 spring-boot-starter-test依赖项来自动包含这些库。

Spring Boot为不同的Spring模块提供了许多依赖项。一些最常用的是:

spring-boot-starter-data-jpaspring-boot-starter-securityspring-boot-starter-testspring-boot-starter-webspring-boot-starter-thymeleaf

有关 starter的完整列表,请查看Spring文档。

MVC配置

让我们来看一下 Spring和 SpringBoot创建 JSPWeb应用程序所需的配置。

Spring需要定义调度程序 servlet,映射和其他支持配置。我们可以使用 web.xml 文件或 Initializer类来完成此操作:

public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setConfigLocation("com.pingfangushi"); container.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic dispatcher = container .addServlet("dispatcher", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }

还需要将 @EnableWebMvc注释添加到 @Configuration类,并定义一个视图解析器来解析从控制器返回的视图:

@EnableWebMvc @Configuration public class ClientWebConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver bean = new InternalResourceViewResolver(); bean.setViewClass(JstlView.class); bean.setPrefix("/WEB-INF/view/"); bean.setSuffix(".jsp"); return bean; } }

再来看 SpringBoot一旦我们添加了 Web启动程序, SpringBoot只需要在 application配置文件中配置几个属性来完成如上操作:

spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp

上面的所有Spring配置都是通过一个名为auto-configuration的过程添加 Bootweb starter来自动包含的。

这意味着 SpringBoot将查看应用程序中存在的依赖项,属性和 bean,并根据这些依赖项,对属性和 bean进行配置。当然,如果我们想要添加自己的自定义配置,那么 SpringBoot自动配置将会退回。

配置模板引擎

现在我们来看下如何在Spring和Spring Boot中配置Thymeleaf模板引擎。

在 Spring中,我们需要为视图解析器添加 thymeleaf-spring5依赖项和一些配置:

@Configuration @EnableWebMvc public class MvcWebConfig implements WebMvcConfigurer { @Autowired private ApplicationContext applicationContext; @Bean public SpringResourceTemplateResolver templateResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(applicationContext); templateResolver.setPrefix("/WEB-INF/views/"); templateResolver.setSuffix(".html"); return templateResolver; } @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.setEnableSpringELCompiler(true); return templateEngine; } @Override public void configureViewResolvers(ViewResolverRegistry registry) { ThymeleafViewResolver resolver = new ThymeleafViewResolver(); resolver.setTemplateEngine(templateEngine()); registry.viewResolver(resolver); } }

SpringBoot1X只需要 spring-boot-starter-thymeleaf的依赖项来启用 Web应用程序中的 Thymeleaf支持。   但是由于 Thymeleaf3.0中的新功能,我们必须将 thymeleaf-layout-dialect 添加为 SpringBoot2XWeb应用程序中的依赖项。配置好依赖,我们就可以将模板添加到 src/main/resources/templates文件夹中, SpringBoot将自动显示它们。

Spring Security 配置

为简单起见,我们使用框架默认的 HTTPBasic身份验证。让我们首先看一下使用 Spring启用 Security所需的依赖关系和配置。

Spring首先需要依赖 spring-security-web和 spring-security-config 模块。接下来, 我们需要添加一个扩展 WebSecurityConfigurerAdapter的类,并使用 @EnableWebSecurity注解:

@Configuration @EnableWebSecurity public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("admin") .password(passwordEncoder() .encode("password")) .authorities("ROLE_ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }

这里我们使用 inMemoryAuthentication来设置身份验证。同样, SpringBoot也需要这些依赖项才能使其工作。但是我们只需要定义 spring-boot-starter-security的依赖关系,因为这会自动将所有相关的依赖项添加到类路径中。

SpringBoot中的安全配置与上面的相同

应用程序启动引导配置

Spring和 SpringBoot中应用程序引导的基本区别在于 servlet。Spring使用 web.xml 或 SpringServletContainerInitializer作为其引导入口点。SpringBoot仅使用 Servlet3功能来引导应用程序,下面让我们详细来了解下

Spring 引导配置

Spring支持传统的 web.xml引导方式以及最新的 Servlet3 方法。

配置 web.xml方法启动的步骤

Servlet容器(服务器)读取 web.xml

web.xml中定义的 DispatcherServlet由容器实例化

DispatcherServlet通过读取 WEB-INF/{servletName}-servlet.xml来创建 WebApplicationContext。最后, DispatcherServlet注册在应用程序上下文中定义的 bean

使用 Servlet3 方法的 Spring启动步骤

容器搜索实现 ServletContainerInitializer的类并执行 SpringServletContainerInitializer找到实现所有类 WebApplicationInitializer``WebApplicationInitializer创建具有XML或上下文 @Configuration类 WebApplicationInitializer创建 DispatcherServlet与先前创建的上下文。

SpringBoot 引导配置

Spring Boot应用程序的入口点是使用@SpringBootApplication注释的类

@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

默认情况下, SpringBoot使用嵌入式容器来运行应用程序。在这种情况下, SpringBoot使用 publicstaticvoidmain入口点来启动嵌入式 Web服务器。此外,它还负责将 Servlet, Filter和 ServletContextInitializerbean从应用程序上下文绑定到嵌入式 servlet容器。SpringBoot的另一个特性是它会自动扫描同一个包中的所有类或 Main类的子包中的组件。

SpringBoot提供了将其部署到外部容器的方式。我们只需要扩展 SpringBootServletInitializer即可:

/** * War部署 * * @author SanLi * Created by 2689170096@qq.com on 2018/4/15 */ public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } @Override public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); servletContext.addListener(new HttpSessionEventPublisher()); } }

这里外部 servlet容器查找在war包下的 META-INF文件夹下MANIFEST.MF文件中定义的 Main-class, SpringBootServletInitializer将负责绑定 Servlet, Filter和 ServletContextInitializer。

打包和部署

最后,让我们看看如何打包和部署应用程序。这两个框架都支持 Maven和 Gradle等通用包管理技术。但是在部署方面,这些框架差异很大。例如,Spring Boot Maven插件在 Maven中提供 SpringBoot支持。它还允许打包可执行 jar或 war包并 就地运行应用程序。

在部署环境中 SpringBoot 对比 Spring的一些优点包括:

1、提供嵌入式容器支持2、使用命令java -jar独立运行jar3、在外部容器中部署时,可以选择排除依赖关系以避免潜在的jar冲突4、部署时灵活指定配置文件的选项5、用于集成测试的随机端口生成

结论

简而言之,我们可以说 SpringBoot只是 Spring本身的扩展,使开发,测试和部署更加方便。项目源码资料获取方式:关注小编 转发文章 私信【 666 】免费获取!!!Java八股文面试资料获取方式:关注小编 转发文章 私信【 13 】免费获取!!!

,