微信小程序接口注册/登陆接口及界面开发实战(三)

引言

  个人认为,相比前端开发,后端开发明显更注重逻辑思维,更注重代码的模块化,追求的低内聚,高可用,这其实也正是前端框架
组件化开发的思想内核,所以即便没有前端框架基础,后端开发人员学习前端可谓是‘降维打击’。笔者认为MVC三层架构的思想核心
即在于分层,为何要分层?初学者经常会有这种疑问,大家可以类比工厂分工,在流水线生产未到来之前,工人既不方便精细化管理,
生产效率也不高,流水线让工人们各司其职,更便于发现问题和解决问题。代码分层的目的也是如此,提升开发的效率,让各大中间件
可以与框架有机结合,也极大的方便了后期的项目维护。
一.创建数据库,数据表
//分析需求 -> 抽象数据模型 -> 设计数据库
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;
二.初始化项目
官方地址:https://start.spring.io/   
添加Web,MyBatis,Mysql相关依赖
建议jdk版本:1.8
三.划分基本项目模块

微信小程序接口注册/登陆接口及界面开发实战(三)_第1张图片

四.编写项目基本配置
#配置启动端口
server.port=9000

#==============================数据库相关配置========================================
spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/wx_user?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username =root
spring.datasource.password =123456

#使用阿里巴巴druid数据源,默认使用自带的
#spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
#开启控制台打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

# mybatis 下划线转驼峰配置,两者都可以
#mybatis.configuration.mapUnderscoreToCamelCase=true
mybatis.configuration.map-underscore-to-camel-case=true
#配置扫描
五.结合数据表编写实体类

数据库与java类的映射(数据类型)

JDBC Type           Java Type 

CHAR                String 
VARCHAR             String 
LONGVARCHAR         String 
NUMERIC             java.math.BigDecimal 
DECIMAL             java.math.BigDecimal 
BIT                 boolean 
BOOLEAN             boolean 
TINYINT             byte 
SMALLINT            short 
INTEGER             INTEGER 
INTEGER       int
BIGINT              long 
REAL                float 
FLOAT               double 
DOUBLE              double 
BINARY              byte[] 
VARBINARY           byte[] 
LONGVARBINARY       byte[] 
DATE                java.sql.Date 
TIME                java.sql.Time 
TIMESTAMP           java.sql.Timestamp 
CLOB                Clob 
BLOB                Blob 
ARRAY               Array 
DISTINCT            mapping of underlying type 
STRUCT              Struct 
REF                 Ref 
DATALINK            java.net.URL
//User.java
public class User {
    private Integer id;
    private String name;
    private String pwd;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

六.编写dao层,整合Mybatis实现数据库插入,查询操作
//UserMapper.java

import com.example.test.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;


public interface UserMapper {

   @Select("select * from user where name = #{name} and pwd = #{pwd}")
    User findByNameAndPwd(String name, String pwd);

   @Insert("insert into user (name,pwd) values (#{name},#{pwd})")
   Integer save(User user);
}

七.引入JsonData工具类,标准化接口返回内容
package com.example.test.utils;

public class JsonData {

    /**
     * 状态码 0表示成功过,1表示处理中,-1 表示失败
     */
    private Integer code;

    /**
     * 业务数据
     */
    private Object data;

    /**
     * 信息表示
     */
    private String msg;

    public JsonData(){}

    public JsonData(Integer code, Object data, String msg){
        this.code = code;
        this.data = data;
        this.msg = msg;
    }


    /**
     * 成功,不用返回数据
     * @return
     */
    public static JsonData buildSuccess(){
        return new JsonData(0,null,null);
    }

    /**
     * 成功,返回数据
     * @param data
     * @return
     */
    public static JsonData buildSuccess(Object data){
        return new JsonData(0,data,null);
    }


    /**
     * 失败,固定状态码
     * @param msg
     * @return
     */
    public static JsonData buildError(String  msg){
        return new JsonData(-1 ,null,msg);
    }


    /**
     * 失败,自定义错误码和信息
     * @param code
     * @param msg
     * @return
     */
    public static JsonData buildError(Integer code , String  msg){
        return new JsonData(code ,null,msg);
    }


    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

八.编写service层,controller层
//UserService.java
import com.example.test.domain.User;


public interface UserService {
    User findByNameAndPwd(String name, String pwd);

    Integer save(User user);
}
//UserServiceImpl.java
import com.example.test.domain.User;
import com.example.test.mapper.UserMapper;
import com.example.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByNameAndPwd(String name, String pwd) {
        return userMapper.findByNameAndPwd(name,pwd);
    }

    @Override
    public Integer save(User user) {
        return userMapper.save(user);
    }
}


//UserController.java
package com.example.test.controller;

import com.example.test.domain.User;
import com.example.test.service.UserService;
import com.example.test.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: ck
 * @Description:
 * @Date: Create in 20:18 2020/7/25
 */
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/helloworld")
    public String HelloWorld()
    {
        return "hello world";
    }

    @RequestMapping("login")
    public JsonData login(@RequestBody User user)
    {
        if(userService.findByNameAndPwd(user.getName(),user.getPwd())!=null)
           return JsonData.buildSuccess("登陆成功");
        return JsonData.buildError("登陆失败");

    }

    @RequestMapping("register")
    public JsonData register(@RequestBody User user)
    {
        userService.save(user);
        return JsonData.buildSuccess("注册成功");
    }
}


你可能感兴趣的:(微信小程序)