Android与spring mybatis交互 实现登录注册

前言

成为全栈的第一步!

UI设计

实现的功能是登录与注册,所以要写两个页面 一个登陆一个注册
这些页面的实现不难,可以拿下面的参考

activity_login.xml 登录界面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#ffffff"
    android:orientation="vertical"

    tools:context=".Activity.Activity_Login">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="70dp"
    android:layout_marginStart="@dimen/dimen_50"
    android:text="@string/login_welcome_1"
    android:textStyle="bold"
    android:textSize="30sp"
    />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/dimen_50"
        android:text="@string/login_welcome_2"
        android:textStyle="bold"
        android:textSize="30sp"
        />
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/ed_account"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_45"
        android:layout_marginTop="90dp"
        android:layout_marginStart="@dimen/dimen_50"
        android:layout_marginEnd="@dimen/dimen_40"
        android:paddingStart="@dimen/dimen_10"
        android:hint="请输入账号"
        android:background="#F8F8F8"
        tools:ignore="RtlSymmetry" />
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/ed_password"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_45"
        android:layout_marginTop="@dimen/dimen_10"
        android:layout_marginStart="@dimen/dimen_50"
        android:layout_marginEnd="@dimen/dimen_40"
        android:paddingStart="@dimen/dimen_10"
        android:hint="请输入密码"
        android:background="#F8F8F8"
        />
    <Button
        android:id="@+id/btn_login"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_45"
        android:layout_marginTop="@dimen/dimen_40"
        android:layout_marginStart="@dimen/dimen_45"
        android:layout_marginEnd="35dp"
        android:paddingStart="@dimen/dimen_10"
       android:text="@string/login"
        android:background="#2196F3"
        tools:ignore="RtlSymmetry" />
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="35dp"
        android:layout_marginStart="@dimen/dimen_40"
        android:layout_marginTop="@dimen/dimen_10"
        >
        <TextView
            android:id="@+id/tv_new"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_new"
            android:layout_gravity="left"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/btn_login"
            tools:ignore="NotSibling,RtlHardcoded" />
        <TextView
            android:id="@+id/tv_lose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login_losePaw"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@id/btn_login"
            tools:ignore="NotSibling" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>

activity_logon.xml 注册页面

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:context=".Activity.Activity_Login">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp"
        android:layout_marginStart="@dimen/dimen_50"
        android:text="欢迎注册XXX"
        android:textStyle="bold"
        android:textSize="30sp"
        />
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/ed_account"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_45"
        android:layout_marginTop="80dp"
        android:layout_marginStart="@dimen/dimen_50"
        android:layout_marginEnd="@dimen/dimen_40"
        android:paddingStart="@dimen/dimen_10"
        android:hint="请输入账号"
        android:background="#F8F8F8"
        tools:ignore="RtlSymmetry" />
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/ed_password"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_45"
        android:layout_marginTop="@dimen/dimen_10"
        android:layout_marginStart="@dimen/dimen_50"
        android:layout_marginEnd="@dimen/dimen_40"
        android:paddingStart="@dimen/dimen_10"
        android:hint="请输入密码"
        android:background="#F8F8F8"
        />
    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/ed_cpassword"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dimen_45"
    android:layout_marginTop="@dimen/dimen_10"
    android:layout_marginStart="@dimen/dimen_50"
    android:layout_marginEnd="@dimen/dimen_40"
    android:paddingStart="@dimen/dimen_10"
    android:hint="确认密码"
    android:background="#F8F8F8"
    tools:ignore="RtlSymmetry" />
    <Button
        android:id="@+id/btn_logon"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_45"
        android:layout_marginTop="@dimen/dimen_40"
        android:layout_marginStart="@dimen/dimen_45"
        android:layout_marginEnd="35dp"
        android:paddingStart="@dimen/dimen_10"
        android:text="@string/logon"
        android:background="#2196F3"
        tools:ignore="RtlSymmetry" />

</LinearLayout>

在这里插入图片描述

spring mybatis设计

该项负责提供接口返回JSON数据

Android利用网络请求进行然后数据库的操作

如果spring mybatis还没入门的,可以去看我的博客简单入门一下:
spring 集成mybatis编写后端接口

UserController.java

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.servlet.UserServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/User")
public class UserController {
    
    

    @Autowired
    private UserServlet userServlet;

    /**
     * 查找用户
     * @param
     * @return
     */
    @RequestMapping("/{account}")
    public User GetUser(@PathVariable String account){
    
    

       return userServlet.Sel(account);
    }

    /**
     *
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/addUser")
    public String Logon(@RequestParam String account,@RequestParam String password){
    
    
        System.out.println("执行了Controller");
         userServlet.Ins(account,password);
        return "成功";
    }
}


UserMapper.xml 负责数据库语句的

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMap">
    <!--数据库查询语句
    id是接口名字 resultType是实体类的路径
    -->
    <select id="Sel" resultType="com.example.demo.entity.User">
        select * from user where account = #{
    
    account}
    </select>

    <insert id="Ins" parameterType="com.example.demo.entity.User">
        insert into user(account,password) values (#{
    
    account},#{
    
    password})
    </insert>
</mapper>

功能实现

该实例用的是Okhttp3进行网络请求

所以要进行添加依赖 下载下来

因为返回的是json数据 ,所以还要用到Gson进行json数据的解析
在这里插入图片描述创建与数据库一致的User实体类 get、set方法

package com.example.toys.entity;

public class User {
    
    
    int id;
    String account;
    String password;

    public int getId() {
    
    
        return id;
    }

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

    public String getAccount() {
    
    
        return account;
    }

    public void setAccount(String account) {
    
    
        this.account = account;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
}

还有别忘了加上网络权限
在 AndroidManifest.xml

  <uses-permission android:name="android.permission.INTERNET"/>

1、登录功能

(1)、获取到账号框和密码框输入的String 先进行一些逻辑判断,如不能为空格,长度不能小于0

(2)、点击登录按钮后 进行网络请求 去数据库查询 返回User实体类之后用Gson解析

(3)、获取到返回的User后判断其密码是否正确,如正确跳转到主页,如不正确输出账号或密码错误等提示信息

ActivityLogin.java 看解析很快就会

package com.example.toys.Activity;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.toys.R;
import com.example.toys.entity.User;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ActivityLogin extends AppCompatActivity implements View.OnClickListener{
    
    
    private EditText edAccount;
    private EditText edPassword;
    private TextView tvLose;
    private TextView tvNew;
    private Button btnLogin;
    private Intent intent;

    RequestBody requestBody;
    OkHttpClient okHttpClient;
    User user;
    String res;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity__login);
        edAccount = findViewById(R.id.ed_account);
        edPassword = findViewById(R.id.ed_password);
        tvLose = findViewById(R.id.tv_lose);
        tvNew = findViewById(R.id.tv_new);
        btnLogin = findViewById(R.id.btn_login);

        tvLose.setOnClickListener(this);
        tvNew.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        intent = new Intent();
    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            case R.id.tv_new:
                intent.setClass(ActivityLogin.this, ActivityLogon.class);
                startActivity(intent);
                return;
            case R.id.btn_login:
                String account = edAccount.getText().toString().trim();
                String password = edPassword.getText().toString().trim();
                if (account.length()<=0 ||password.length()<=0)
                    Toast.makeText(ActivityLogin.this,"请正确输入",Toast.LENGTH_SHORT).show();
                else
                    login(account,password);
                return;
        }

    }

    private void login(final String account, final String password) {
    
    
//设置请求参数
        FormBody.Builder formBody = new FormBody.Builder();
        formBody.add("account",account);

        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .callTimeout(3000, TimeUnit.SECONDS)
                .build();
        requestBody = formBody.build();
        //Okhttp3同步请求 开启线程
      Thread thread =  new Thread() {
    
    
            @Override
            public void run() {
    
    
                //设置请求的地址
                Request request = new Request.Builder()
                                             .url("http://172.20.10.5:8080/User/"+account)
                                             .post(requestBody).build();
                Response response = null;
                try {
    
    
                    //同步请求
                    response = okHttpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
    
    
                        res = response.body().string();
                        //Gson解析
                        Gson gson = new Gson();
                         user = gson.fromJson(res,User.class);
                    } else{
    
    
                        System.out.println("服务器连接失败");
                         return;
                    }
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
                return;
            }
        };
      //start开启线程 ,join()主线程等待子线程执行完成在继续执行
      thread.start();
        try {
    
    
            thread.join();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        //判断密码是否正确 正确后进行跳转
        if (user!=null && user.getPassword().equals(password)){
    
    
            Intent intent = new Intent(ActivityLogin.this, ActivityMy.class);
            startActivity(intent);
            finish();
        }else
            Toast.makeText(ActivityLogin.this,"账号或密码错误",Toast.LENGTH_SHORT).show();
    }
}

2、注册功能

(1)、获取到账号框、密码框和确认密码框输入的String 先进行一些逻辑判断,如不能为空格,长度不能小于0、密码框与确认密码框内容是否一样

(2)、点击登录按钮后 带上输入的账号和密码作为请求参数,进行网络请求

(3)、如注册成功接口返回"成功”字样,注册成功,之后跳转到首页

ActivityLogon.java 基本与登录一致,拿来参考不做赘述了。

package com.example.toys.Activity;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.toys.ApiConfig;
import com.example.toys.R;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ActivityLogon extends AppCompatActivity implements View.OnClickListener{
    
    
    private EditText edAccount;
    private EditText edPassword;
    private EditText edCPassword;
    private Button btnLogon;
    RequestBody requestBody;
    OkHttpClient okHttpClient;
    String res = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity__logon);
        edAccount = findViewById(R.id.ed_account);
        edPassword = findViewById(R.id.ed_password);
        edCPassword = findViewById(R.id.ed_cpassword);
        btnLogon = findViewById(R.id.btn_logon);
        btnLogon.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            case R.id.btn_logon:
                String account = edAccount.getText().toString();
                String password = edPassword.getText().toString();
                String CPassword = edCPassword.getText().toString();
                //判断一下字符字符串是否符合
                if (account.length()<=0 ||password.length()<=0)
                    Toast.makeText(ActivityLogon.this,"请正确输入",Toast.LENGTH_SHORT).show();
                else if (!CPassword.equals(password)){
    
    
                    Toast.makeText(ActivityLogon.this,"两次密码不一致",Toast.LENGTH_SHORT).show();
                }
                else
                logon(account,password);
                break;
        }
    }

    private void logon(String account, String password) {
    
    

        // 构建请求参数
                        FormBody.Builder formBody = new FormBody.Builder();
                        formBody.add("account",account);
                        formBody.add("password",password);
                        requestBody = formBody.build();


                okHttpClient = new OkHttpClient.Builder()
                                    .connectTimeout(3000, TimeUnit.SECONDS)
                                    .callTimeout(3000, TimeUnit.SECONDS)
                                    .build();

       Thread thread = new Thread() {
    
    
            @Override
            public void run() {
    
    
                Request request = new Request.Builder().url(ApiConfig.LOGIN).post(requestBody).build();
                Response response = null;
                try {
    
    
                    response = okHttpClient.newCall(request).execute();
                    if (response.isSuccessful()) {
    
    
                        res = response.body().string();
                        if (res != null){
    
    
                            return;
                        }
                    } else {
    
    System.out.println("服务器连接失败");
                    return;
                    }
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        };
       thread.start();
        try {
    
    
            thread.join();
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        if (res.equals("成功")){
    
    
            Toast.makeText(ActivityLogon.this,"注册成功",Toast.LENGTH_LONG).show();
            Intent intent = new Intent(ActivityLogon.this, ActivityMy.class);
            startActivity(intent);
            finish();
        }
        else
            Toast.makeText(ActivityLogon.this,"注册失败,请稍后再试...",Toast.LENGTH_LONG).show();
    }
}

测试

(1)、记得运行Idea中的项目
(2)、Url不再是localhost了 改成电脑的ip地址 通过cmd命令 ipconfig查看
(3)、电脑与手机要连接用一个网络

1、注册
在这里插入图片描述

2、登录

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44758662/article/details/109672349
今日推荐