当前位置:   article > 正文

微信程序开发之小程序交互_eclipse开发微信小程序

eclipse开发微信小程序

一、创建登录页面搭建

1、登录界面login.wxml

  1. <view class="mage">
  2. <image src="/assect/Stud.jpg" style="width:200px;height:200px" mode="center"></image>
  3. </view>
  4. <view>
  5. <!-- 11位的电话号码-->
  6. <label>用户名</label>
  7. <input bind:input="changeValue" data-label="account" type="text" placeholder="请输入用户名" maxlength="11"></input>
  8. <label>密码</label>
  9. <input bind:input="changeValue" data-label="password" type="text" placeholder="请输入密码" password="true" maxlength="16"></input>
  10. <button type="primary" bindtap="login">登录</button>
  11. <button form-type="reset" type="primary">清空</button>
  12. </view>

2、登录布局wxss

  1. image{
  2. width: 400px;
  3. height: 400px;
  4. border-radius: 50%;
  5. }
  6. .mage{
  7. display:flex; /*设置为flex布局*/
  8. justify-content: center; /*水平居中*/
  9. }
  10. .container{
  11. display:flex; /*设置为flex布局*/
  12. justify-content: center; /*水平居中*/
  13. }

3、login.js

  1. Page({
  2. data: {
  3. user:{
  4. account:"",
  5. password:"",
  6. }
  7. },
  8. changeValue(e){
  9. console.log(e)
  10. // 取到输入框中的值
  11. let value=e.detail.value
  12. // 拿到标签上的data-label(account/password)
  13. // account->user.account
  14. let label="user."+e.target.dataset.label
  15. this.setData({
  16. [label]:value
  17. })
  18. },
  19. login(){
  20. console.log(this.data.user)
  21. }
  22. })

取到登录的值:

 二、后台开发

1、新建一个springBoot项目

 2、导入依赖pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.lv</groupId>
  6. <artifactId>code</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>wx</name>
  9. <description>Demo project for Spring Boot</description>
  10. <properties>
  11. <java.version>1.8</java.version>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  14. <spring-boot.version>2.4.1</spring-boot.version>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.projectlombok</groupId>
  27. <artifactId>lombok</artifactId>
  28. <optional>true</optional>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-test</artifactId>
  33. <scope>test</scope>
  34. </dependency>
  35. <dependency>
  36. <groupId>mysql</groupId>
  37. <artifactId>mysql-connector-java</artifactId>
  38. </dependency>
  39. <dependency>
  40. <groupId>tk.mybatis</groupId>
  41. <artifactId>mapper-spring-boot-starter</artifactId>
  42. <version>2.0.2</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>javax.persistence</groupId>
  46. <artifactId>persistence-api</artifactId>
  47. <version>1.0</version>
  48. </dependency>
  49. </dependencies>
  50. <dependencyManagement>
  51. <dependencies>
  52. <dependency>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-dependencies</artifactId>
  55. <version>${spring-boot.version}</version>
  56. <type>pom</type>
  57. <scope>import</scope>
  58. </dependency>
  59. </dependencies>
  60. </dependencyManagement>
  61. <build>
  62. <plugins>
  63. <plugin>
  64. <groupId>org.apache.maven.plugins</groupId>
  65. <artifactId>maven-compiler-plugin</artifactId>
  66. <version>3.8.1</version>
  67. <configuration>
  68. <source>1.8</source>
  69. <target>1.8</target>
  70. <encoding>UTF-8</encoding>
  71. </configuration>
  72. </plugin>
  73. <plugin>
  74. <groupId>org.springframework.boot</groupId>
  75. <artifactId>spring-boot-maven-plugin</artifactId>
  76. <version>2.4.1</version>
  77. <configuration>
  78. <mainClass>com.lv.code.WxApplication</mainClass>
  79. </configuration>
  80. <executions>
  81. <execution>
  82. <id>repackage</id>
  83. <goals>
  84. <goal>repackage</goal>
  85. </goals>
  86. </execution>
  87. </executions>
  88. </plugin>
  89. </plugins>
  90. </build>
  91. </project>

3、导入虚拟数据到数据库

 4、生成表的实体类

 注意存放的位置:

实体类User: 

  1. package com.lv.code.pojo;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. import com.fasterxml.jackson.annotation.JsonFormat;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.NoArgsConstructor;
  8. import lombok.experimental.Accessors;
  9. import org.springframework.format.annotation.DateTimeFormat;
  10. import javax.persistence.*;
  11. /**
  12. * t_user
  13. * @author
  14. */
  15. @Data
  16. @Table(name = "t_user")
  17. @AllArgsConstructor
  18. @NoArgsConstructor
  19. @Accessors(chain = true)
  20. public class User implements Serializable {
  21. // 组件自增
  22. @Id
  23. @GeneratedValue(strategy = GenerationType.IDENTITY)
  24. private Long id;
  25. private String account;
  26. private String password;
  27. // 将前端发送的string数据转换为date类型,输出date类型
  28. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  29. // 将date类型转换为string类型,接收date类型
  30. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  31. private Date modifyTime;
  32. // 将前端发送的string数据转换为date类型,输出date类型
  33. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  34. // 将date类型转换为string类型,接收date类型
  35. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  36. private Date createTime;
  37. private static final long serialVersionUID = 1L;
  38. }

5、配置yml文件

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. username: root
  6. password: 123456
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. url: jdbc:mysql://localhost:3306/aaa?userSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true

6、导入util包

JsonResponseParse :

  1. package com.lv.code.util.response;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.core.MethodParameter;
  4. import org.springframework.http.MediaType;
  5. import org.springframework.http.server.ServerHttpRequest;
  6. import org.springframework.http.server.ServerHttpResponse;
  7. import org.springframework.web.bind.annotation.RestControllerAdvice;
  8. import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
  9. @SuppressWarnings("all")
  10. @RestControllerAdvice
  11. @Slf4j
  12. /**
  13. * 响应增强类,配合{@link JsonResponseResult}实现自定义快速返回
  14. * beforeBodyWrite在{@link org.springframework.web.bind.annotation.ResponseBody}完成return之后并在消息解析器之前执行
  15. */
  16. public class JsonResponseParse implements ResponseBodyAdvice {
  17. @Override
  18. /**
  19. * 返回值决定他是否需要进入beforeBodyWrite
  20. */
  21. public boolean supports(MethodParameter methodParameter, Class aClass) {
  22. /*methodParameter是当前执行返回响应的方法,判断在该类上是否存在对应的注解*/
  23. return methodParameter.getMethod().isAnnotationPresent(JsonResponseResult.class);
  24. }
  25. @Override
  26. /**
  27. * 用于修改返回前的值
  28. */
  29. public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
  30. if (o == null) {
  31. return ResponseResult.success();
  32. }
  33. if (o instanceof Integer) {
  34. return ResponseResult.failure(ResponseResultCode.queryCode((Integer) o));
  35. }
  36. if (o instanceof ResponseResultCode) {
  37. return ResponseResult.failure((ResponseResultCode) o);
  38. }
  39. if (o instanceof ResponseResult) {
  40. return o;
  41. }
  42. return ResponseResult.success(o);
  43. }
  44. }

JsonResponseResult :

  1. package com.lv.code.util.response;
  2. import java.lang.annotation.*;
  3. @SuppressWarnings("all")
  4. @Retention(value = RetentionPolicy.RUNTIME)
  5. @Documented
  6. @Target({ElementType.METHOD})
  7. /**
  8. * 此注解用于配合{@link JsonResponseParse}使用
  9. */
  10. public @interface JsonResponseResult {
  11. }

ResponseResult<T>:

  1. package com.lv.code.util.response;
  2. import lombok.Data;
  3. import java.io.Serializable;
  4. @Data
  5. @SuppressWarnings("all")
  6. public class ResponseResult<T> implements Serializable {
  7. // 响应状态码
  8. private Integer code;
  9. // 响应信息
  10. private String message;
  11. // 响应携带数据
  12. private T data;
  13. // 响应分页数据
  14. private Long total;
  15. /**
  16. * 私有构造, 只允许通过static调用构造
  17. *
  18. * @param resultCode 结果枚举
  19. * @param data 响应数据
  20. */
  21. private ResponseResult(ResponseResultCode resultCode, T data) {
  22. this.code = resultCode.getCode();
  23. this.message = resultCode.getMessage();
  24. this.data = data;
  25. }
  26. /**
  27. * 私有构造, 只允许通过static调用构造
  28. *
  29. * @param resultCode 结果枚举
  30. * @param data 响应数据
  31. * @param total 数据总大小(用于分页请求)
  32. */
  33. private ResponseResult(ResponseResultCode resultCode, Long total, T data) {
  34. this.code = resultCode.getCode();
  35. this.message = resultCode.getMessage();
  36. this.data = data;
  37. this.total = total;
  38. }
  39. /**
  40. * 成功调用返回的结果(无数据携带)
  41. */
  42. public static ResponseResult<?> success() {
  43. return success(null);
  44. }
  45. /**
  46. * 成功调用返回的结果(数据携带)
  47. *
  48. * @param data 携带的数据
  49. */
  50. public static <T> ResponseResult success(T data) {
  51. return new ResponseResult(ResponseResultCode.SUCCESS, data);
  52. }
  53. /**
  54. * 成功调用返回的结果(分页使用)
  55. *
  56. * @param data 携带的数据
  57. * @param total 数据总条数
  58. */
  59. public static <T> ResponseResult success(T data, Long total) {
  60. return new ResponseResult(ResponseResultCode.SUCCESS, total, data);
  61. }
  62. /**
  63. * 失败调用返回的结果(数据携带)
  64. *
  65. * @param resultCode 状态枚举
  66. * @param data 携带的数据
  67. */
  68. public static <T> ResponseResult failure(ResponseResultCode resultCode, T data) {
  69. return new ResponseResult(resultCode, data);
  70. }
  71. /**
  72. * 失败调用返回的结果(无数据携带)
  73. *
  74. * @param resultCode 状态枚举
  75. */
  76. public static ResponseResult failure(ResponseResultCode resultCode) {
  77. return failure(resultCode, null);
  78. }
  79. }

ResponseResultCode :

  1. package com.lv.code.util.response;
  2. import java.io.Serializable;
  3. public enum ResponseResultCode implements Serializable {
  4. /* 正常状态 */
  5. SUCCESS(200, "成功"),
  6. FAILURE(300, "失败"),
  7. UNKNOWN(400, "未知错误"),
  8. /**
  9. * 用户code范围: 1000;
  10. */
  11. USER_ACCOUNT_NOT_FIND(1001, "用户名不存在"),
  12. USER_ACCOUNT_DISABLED(1002, "该用户已被禁用"),
  13. USER_PASSWORD_NOT_MATCH(1003, "该用户密码不一致"),
  14. USER_PERMISSION_ERROR(1004, "该用户不具备访问权限"),
  15. USER_STATE_OFF_LINE(1005, "该用户未登录"),
  16. USER_CREDENTIAL_NOT_BE_EMPTY(1006, "用户的登录信息不能为空值"),
  17. USER_ACCOUNT_NOT_MOBLIE(1007, "该用户登录信息格式不符合"),
  18. USER_LOGIN_ERROR(1008, "登录失败"),
  19. /**
  20. * 其它异常: 4000;
  21. */
  22. TRIKET_ERROR(4001, "triket失效,请重新登录"),
  23. /**
  24. * 商品异常: 6000;
  25. */
  26. GOODS_ADD_ERROR(6001, "商品添加失败"),
  27. GOODS_EDIT_ERROR(6002, "商品修改失败"),
  28. GOODS_REMOVE_ERROR(6003, "商品删除失败");
  29. /*响应状态码*/
  30. private final Integer code;
  31. /*响应状态信息*/
  32. private final String message;
  33. /*此构造无法调用,用来定义常量枚举使用*/
  34. ResponseResultCode(Integer code, String message) {
  35. this.code = code;
  36. this.message = message;
  37. }
  38. /**
  39. * 此方法用于配合{@link JsonResponseParse}实现快速返回json类型响应码
  40. * 需要结合{@link JsonResponseResult}注解使用
  41. *
  42. * @param code 响应码(对应枚举中的code,如无法找到则返回`UNKNOWN`)
  43. */
  44. public static ResponseResultCode queryCode(Integer code) {
  45. for (ResponseResultCode value : values()) {
  46. if (code.equals(value.code)) {
  47. return value;
  48. }
  49. }
  50. return UNKNOWN;
  51. }
  52. public Integer getCode() {
  53. return code;
  54. }
  55. public String getMessage() {
  56. return message;
  57. }
  58. }

ThrowableAdvice :

  1. package com.lv.code.util.response;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.web.bind.annotation.RestControllerAdvice;
  4. @SuppressWarnings("all")
  5. @Slf4j
  6. @RestControllerAdvice
  7. public class ThrowableAdvice {
  8. /**
  9. @JsonResponseResult
  10. @ExceptionHandler(value = {BusinessException.class})
  11. public ResponseResultCode globalBusinessException(Model m, Exception e) {
  12. log.error(e.toString());
  13. return ((BusinessException) e).getResponseResultCode();
  14. }
  15. @JsonResponseResult
  16. @ExceptionHandler(value = {BindException.class})
  17. public ResponseResultCode globalBindException(Model m, Exception e) {
  18. log.error(e.toString());
  19. BindException error = (BindException) e;
  20. return (ResponseResultCode) error.getFieldError().getArguments()[1];
  21. }
  22. @JsonResponseResult
  23. @ExceptionHandler(value = {Throwable.class})
  24. public ResponseResultCode globalException(Model m, Exception e) {
  25. log.error(e.toString());
  26. return ResponseResultCode.UNKNOWN;
  27. }
  28. **/
  29. }

7、新建mapper层

UserMapper.java:

  1. package com.lv.code.mapper;
  2. import com.lv.code.pojo.User;
  3. import org.springframework.stereotype.Repository;
  4. import tk.mybatis.mapper.common.Mapper;
  5. @Repository
  6. public interface UserMapper extends Mapper<User> {
  7. }

8、在启动类增加注解扫描mapper层

@MapperScan("com.lv.code.mapper")

9、新建service层

接口IuserService :

  1. package com.lv.code.service;
  2. import com.lv.code.pojo.User;
  3. import com.lv.code.util.response.ResponseResult;
  4. public interface IuserService {
  5. ResponseResult<?> findUserByAccount(User user);
  6. }

实现接口userServiceImpl :

  1. package com.lv.code.service.impl;
  2. import com.lv.code.mapper.UserMapper;
  3. import com.lv.code.pojo.User;
  4. import com.lv.code.service.IuserService;
  5. import com.lv.code.util.response.ResponseResult;
  6. import com.lv.code.util.response.ResponseResultCode;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import org.springframework.util.StringUtils;
  10. import tk.mybatis.mapper.entity.Example;
  11. @Service
  12. public class userServiceImpl implements IuserService {
  13. @Autowired
  14. private UserMapper userMapper;
  15. @Override
  16. public ResponseResult<?> findUserByAccount(User user) {
  17. if(StringUtils.isEmpty(user.getAccount())){
  18. return ResponseResult.failure(ResponseResultCode.USER_CREDENTIAL_NOT_BE_EMPTY);
  19. }
  20. // 声明一个条件载体
  21. Example example=new Example(User.class);
  22. // 放入一个条件
  23. example.createCriteria().andEqualTo("account",user.getAccount());
  24. // 使用条件载体进行查询
  25. User u=userMapper.selectOneByExample(example);
  26. if(u==null){
  27. return ResponseResult.failure(ResponseResultCode.USER_ACCOUNT_NOT_FIND);
  28. }
  29. if(user.getPassword().equals(u.getPassword())){
  30. return ResponseResult.failure(ResponseResultCode.USER_PASSWORD_NOT_MATCH);
  31. }
  32. return ResponseResult.success(u);
  33. }
  34. }

10、新建controller层

  1. package com.lv.code.controller;
  2. import com.lv.code.pojo.User;
  3. import com.lv.code.service.IuserService;
  4. import com.lv.code.util.response.ResponseResult;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.scheduling.annotation.Async;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. @RestController
  11. @RequestMapping("/user")
  12. public class UserController {
  13. @Autowired
  14. private IuserService userService;
  15. @RequestMapping("/login")
  16. public ResponseResult<?> login(@RequestBody User user){
  17. return userService.findUserByAccount(user);
  18. }
  19. }

11、测试登录

使用户名与密码正确输入:

登录成功:

 三、前后台交互

微信request的特征:它去网络通信的时候是异步的,若想要同步,则使用Promise风格,微信小程序不支持,需要自己编写。

1、在前端新建一个文件夹

内包含JavaScript文件:index.js

  1. export let request=(url,data)=>{
  2. // 写上natapp提供的域名
  3. let baseURL="http://localhost:8080"
  4. // 异步代码
  5. return new Promise((resolve,reject)=>{
  6. wx.request({
  7. url: baseURL+url,
  8. data,
  9. timeout:4000,
  10. method:"POST",
  11. dataType:"json",
  12. success:(res)=>resolve(res),
  13. fail:(res)=>reject(res)
  14. })
  15. })
  16. }

login.js调用:

  1. // 直接导入index.js模块
  2. import {request} from "../../request/index";
  3. Page({
  4. data: {
  5. user:{
  6. account:"",
  7. password:""
  8. }
  9. },
  10. changeValue(e){
  11. // 取到输入框中的值
  12. let value=e.detail.value
  13. // 拿到标签上的data-label(account/password)
  14. // account->user.account
  15. let label="user."+e.target.dataset.label
  16. this.setData({
  17. [label]:value
  18. })
  19. },
  20. login(){
  21. wx.showLoading({
  22. title:"正在拼命加载中",
  23. mask:false
  24. })
  25. request("/user/login",this.data.user).then(res=>{
  26. console.log(res)
  27. wx.hideLoading()
  28. let icon="success"
  29. if(res.data.code!==200){
  30. icon="error"
  31. }
  32. wx.showToast({
  33. icon,
  34. title:res.data.message
  35. })
  36. }).catch(res=>{
  37. console.error(res)
  38. wx.hideLoading()
  39. })
  40. }
  41. })

登录成功:

 

本期内容结束~~~~~~~~~~~~~~~~~~~~~~~~~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/711471
推荐阅读