当前位置:   article > 正文

微信小程序开发之微信小程序交互_微信小程序前后端交互

微信小程序前后端交互

目录

一、小程序交互

前端:

1、先在登陆界面中编写代码

2、在前端中编写js代码

后端:

          1、先导入依赖:

          2、定义好配置文件

          3、编写好实体类

          4、将帮助类进行配置

          5、编写mapper类

          6、定义service层以及对应的实现接口层

          7、最后定义controller层

          8、进行测试


一、小程序交互

步骤:

前端:

1、先在登陆界面中编写代码

login.wxml:

  1. <view>
  2. <image src="/png/b.jpg" mode="scaleToFill"/>
  3. <view>
  4. <input placeholder="请输入用户名" maxlength="13" bind:input="changeValue" data-label="account"/>
  5. </view>
  6. <view>
  7. <input placeholder="请输入密码" password="{{true}}" bind:input="changeValue" maxlength="16" data-label="password"/>
  8. </view>
  9. <view>
  10. <button bindtap="userLogin" type="primary">登录</button>
  11. </view>
  12. </view>

2、在前端中编写js代码

  1. import {request} from "../../request/index";
  2. Page({
  3. data: {
  4. user: {
  5. account: "",
  6. password: ""
  7. }
  8. },
  9. changeValue(e) {
  10. let property = "user." + e.target.dataset.label
  11. let value = e.detail.value
  12. this.setData({
  13. [property]: value
  14. })
  15. },
  16. userLogin() {
  17. wx.showLoading({
  18. title: "正在努力加载中",
  19. mask: false
  20. })
  21. request("/user/login", this.data.user).then(res => {
  22. console.log(res)
  23. wx.hideLoading()
  24. let icon = "error"
  25. if (res.data.code === 200) {
  26. icon = "success"
  27. }
  28. wx.showToast({
  29. title: res.data.message,
  30. icon
  31. })
  32. }).catch(res => {
  33. console.error(res)
  34. wx.hideLoading()
  35. })
  36. }
  37. })

后端:

          1、先导入依赖:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.projectlombok</groupId>
  8. <artifactId>lombok</artifactId>
  9. <optional>true</optional>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-test</artifactId>
  14. <scope>test</scope>
  15. </dependency>
  16. <dependency>
  17. <groupId>mysql</groupId>
  18. <artifactId>mysql-connector-java</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>tk.mybatis</groupId>
  22. <artifactId>mapper-spring-boot-starter</artifactId>
  23. <version>2.1.5</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>javax.persistence</groupId>
  27. <artifactId>persistence-api</artifactId>
  28. <version>1.0</version>
  29. </dependency>
  30. </dependencies>
  31. <dependencyManagement>
  32. <dependencies>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-dependencies</artifactId>
  36. <version>${spring-boot.version}</version>
  37. <type>pom</type>
  38. <scope>import</scope>
  39. </dependency>
  40. </dependencies>
  41. </dependencyManagement>
  42. <build>
  43. <plugins>
  44. <plugin>
  45. <groupId>org.apache.maven.plugins</groupId>
  46. <artifactId>maven-compiler-plugin</artifactId>
  47. <version>3.8.1</version>
  48. <configuration>
  49. <source>1.8</source>
  50. <target>1.8</target>
  51. <encoding>UTF-8</encoding>
  52. </configuration>
  53. </plugin>
  54. <plugin>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-maven-plugin</artifactId>
  57. <version>2.4.1</version>
  58. <configuration>
  59. <mainClass>com.zking.mini_program.MiniProgramApplication</mainClass>
  60. </configuration>
  61. <executions>
  62. <execution>
  63. <id>repackage</id>
  64. <goals>
  65. <goal>repackage</goal>
  66. </goals>
  67. </execution>
  68. </executions>
  69. </plugin>
  70. </plugins>
  71. </build>

          2、定义好配置文件

server:
    port: 8080
spring:
    application:
        name: mini_program
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
        password: password
        url: jdbc:mysql://127.0.0.1/wechat?useSSL=false&serverTimezone=Asia/Shanghai&useEncoding=utf8mb4

          3、编写好实体类

  1. import com.fasterxml.jackson.annotation.JsonFormat;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import lombok.experimental.Accessors;
  6. import org.springframework.format.annotation.DateTimeFormat;
  7. import javax.persistence.*;
  8. import java.io.Serializable;
  9. import java.time.LocalDateTime;
  10. @Data
  11. @Table(name = "t_user")
  12. @AllArgsConstructor
  13. @NoArgsConstructor
  14. @Accessors(chain = true)
  15. @SuppressWarnings("all")
  16. public class User implements Serializable {
  17. @Id
  18. @GeneratedValue(strategy = GenerationType.IDENTITY)
  19. private Long id;
  20. private String account;
  21. private String password;
  22. @Column(name = "modify_time")
  23. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  24. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  25. private LocalDateTime modifyTime;
  26. @Column(name = "create_time")
  27. @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  28. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  29. private LocalDateTime createTime;
  30. }

          4、将帮助类进行配置

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

2、json响应结果类

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

3、响应结果类

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

4、响应编码类:

  1. import java.io.Serializable;
  2. @SuppressWarnings("all")
  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. }

 5、异常辅助类:

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

          5、编写mapper类

  1. @SuppressWarnings("all")
  2. @Repository
  3. public interface UserMapper extends Mapper<User> {
  4. }

          6、定义service层以及对应的实现接口层

service:

  1. @SuppressWarnings("all")
  2. public interface IUserService {
  3. ResponseResult<?> findUserByAccount(User user);
  4. }

其中ResponseResult<?>响应结果类,中的?是可以随便放什么类的

E:一个集合的元素

K:键

V:值

T:类

          7、最后定义controller层

  1. @SuppressWarnings("all")
  2. @RequestMapping("/user")
  3. @RestController
  4. public class UserController {
  5. @Autowired
  6. private IUserService userService;
  7. @RequestMapping("/login")
  8. public ResponseResult<?> login(@RequestBody User user) {
  9. return userService.findUserByAccount(user);
  10. }
  11. }

          8、进行测试

 输入账号和密码进行登录

 成功!

输入错误密码就会显示和该用户密码不统一

今天的知识就分享到这了,希望能够帮助到你!

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

闽ICP备14008679号