安卓端調用服務器登錄函數進行驗證登錄
觀前提示:本系列文章有關服務器以及后端程序這些概念,我寫的全是自己的理解,並不一定正確,希望不要誤人子弟。歡迎各位大佬來評論區提出問題或者是指出錯誤,分享寶貴經驗。先謝謝了( ̄▽ ̄)"!
前面兩篇算是鋪墊了一下后端項目的基本工作流程,本周就講一下前后端的簡單互動——聯網登錄。
關於這個安卓端的項目,我個人是跟着下面鏈接里的教程學習的,這個登錄功能算是我自己對學到的東西的一個運用,有興趣的朋友可以去看看原文,是一個網上商城APP的范例:
老規矩,文中主要用到的代碼會在相應位置貼出來,話不多說咱們馬上進入正題!
客戶端的實現:
- XML布局:

1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".LoginActivity"> 8 9 <TextView 10 android:id="@+id/title" 11 android:layout_width="350dp" 12 android:layout_height="wrap_content" 13 android:layout_marginTop="130dp" 14 android:layout_marginLeft="32dp" 15 android:text="登錄" 16 android:textSize="36sp" 17 android:textStyle="bold" /> 18 19 <EditText 20 android:id="@+id/username" 21 android:layout_width="350dp" 22 android:layout_height="wrap_content" 23 android:layout_below="@+id/title" 24 android:layout_marginLeft="28dp" 25 android:layout_marginTop="35dp" 26 android:hint="請輸入用戶名" 27 android:singleLine="true" /> 28 29 <EditText 30 android:id="@+id/password" 31 android:layout_width="350dp" 32 android:layout_height="wrap_content" 33 android:layout_below="@+id/username" 34 android:layout_marginLeft="28dp" 35 android:layout_marginTop="20dp" 36 android:hint="請輸入密碼" 37 android:inputType="textPassword" 38 android:singleLine="true" /> 39 40 <Button 41 android:id="@+id/login" 42 android:layout_width="350dp" 43 android:layout_height="wrap_content" 44 45 android:layout_below="@+id/password" 46 android:layout_marginLeft="28dp" 47 android:layout_marginTop="25dp" 48 android:background="#E91E63" 49 android:text="登錄" 50 android:textColor="#000000" 51 android:textSize="18sp" /> 52 53 <TextView 54 android:id="@+id/modify" 55 android:layout_width="wrap_content" 56 android:layout_height="wrap_content" 57 android:layout_below="@+id/login" 58 android:layout_marginLeft="32dp" 59 android:layout_marginTop="15dp" 60 android:text="修改/忘記密碼" 61 android:textColor="#03A9F4" /> 62 63 <TextView 64 android:id="@+id/register" 65 android:layout_width="wrap_content" 66 android:layout_height="wrap_content" 67 android:layout_below="@+id/login" 68 android:layout_marginLeft="180dp" 69 android:layout_marginTop="15dp" 70 android:layout_toRightOf="@+id/modify" 71 android:text="注冊新用戶" 72 android:textColor="#03A9F4" /> 73 74 </RelativeLayout>
- Activity代碼:

1 package com.example.dolphin; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.content.Intent; 6 import android.os.Bundle; 7 import android.widget.Button; 8 import android.widget.EditText; 9 import android.widget.Toast; 10 11 import com.example.dolphin.utils.Constants; 12 import com.zhy.http.okhttp.OkHttpUtils; 13 import com.zhy.http.okhttp.callback.StringCallback; 14 15 import butterknife.BindView; 16 import butterknife.ButterKnife; 17 import okhttp3.Call; 18 19 public class LoginActivity extends AppCompatActivity { 20 21 @BindView(R.id.username) 22 EditText name; 23 @BindView(R.id.password) 24 EditText key; 25 @BindView(R.id.login) 26 Button login; 27 28 @Override 29 protected void onCreate(Bundle savedInstanceState) { 30 super.onCreate(savedInstanceState); 31 setContentView(R.layout.activity_login); 32 ButterKnife.bind(this); 33 login.setOnClickListener(view-> 34 new Thread(()->getDataFromNet()).start() 35 ); 36 } 37 private void getDataFromNet() { 38 String url = Constants.LOGIN_URL; 39 OkHttpUtils 40 .get() 41 .url(url) 42 .addParams("name",name.getText().toString()) 43 .addParams("key",key.getText().toString()) 44 .build() 45 .execute(new StringCallback() 46 { 47 /** 48 * 請求失敗的時候回調 49 * @param call 50 * @param e 51 * @param id 52 */ 53 @Override 54 public void onError(Call call, Exception e, int id) { 55 System.out.println("首頁請求失敗=="+e.getMessage()); 56 } 57 /** 58 * 當請求成功的時候回調 59 * @param response 請求成功數據 60 * @param id 61 */ 62 @Override 63 public void onResponse(String response, int id) { 64 System.out.println("首頁請求成功=="+response); 65 //解析數據 66 processData(response); 67 } 68 }); 69 } 70 71 private void processData(String json) { 72 System.out.println(json); 73 if(json.equals("YES")){ 74 Toast.makeText(this,"登陸成功",Toast.LENGTH_SHORT).show(); 75 Intent intent = new Intent(this, MainActivity.class); 76 startActivity(intent); 77 }else 78 Toast.makeText(this,"用戶名或者密碼錯誤",Toast.LENGTH_SHORT).show(); 79 } 80 }
這里用到了鴻洋大神封裝好的 okhttp3 以及插件ButterKnife(黃油刀),其主要功能分別如下:
okhttp-utils(目前對以下需求進行了封裝):
- 一般的get請求
- 一般的post請求
- 基於Http Post的文件上傳(類似表單)
- 文件下載/加載圖片
- 發布下載的進度預期
- 支持取消某個請求
- 支持自定義回調
- 支持HEAD,DELETE,PATCH,PUT
- 支持會議的保持
- 支持自簽名網站https的訪問,提供方法設置下證書就行
如何引入依賴以及詳細介紹請移步到這位大神的Github:https://github.com/hongyangAndroid/okhttputils
ButterKnife(黃油刀):
ButterKnife是一個專注於Android系統的View注入框架,以前總是要寫很多findViewById來找到View對象,有了ButterKnife可以很輕松的省去這些步驟。是大神JakeWharton的力作,目前使用很廣。最重要的一點,使用ButterKnife對性能基本沒有損失,因為ButterKnife用到的注解並不是在運行時反射的,而是在編譯的時候生成新的class。項目集成起來也是特別方便,使用起來也是特別簡單。
使用與配置方法總結見這里:https://www.cnblogs.com/chenxibobo/p/9633086.html
還有就是為了避免每次進行get或者post請求時都會填寫很長的url地址,我新建了一個公共類保存這些靜態變量,如下圖:
同時記得把地址和端口號填寫正確,而且確保要訪問的服務器正在運行,不然會出現如下錯誤提示(寫在代碼里了):
WEB端的實現:
- LoginController(登錄控制層)

1 package dolphin.controller; 2 3 import dolphin.service.UserService; 4 import org.springframework.stereotype.Controller; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import dolphin.utils.Singleton; 7 import org.springframework.web.bind.annotation.ResponseBody; 8 9 import javax.servlet.http.HttpServletRequest; 10 11 /** 12 * 登錄控制層 13 * @author 郭小柒w 14 * @date 2020/3/25 21:18 15 */ 16 @Controller 17 public class LoginController { 18 private UserService userService = (UserService) Singleton.GetApplicationContext().getBean("UserServiceImpl"); 19 /** 20 * @Description :登陸驗證 21 * @return :java.lang.String 22 **/ 23 @ResponseBody 24 @RequestMapping("/Login") 25 public String check(HttpServletRequest request){ 26 //獲取請求中的參數,用戶名和密碼 27 String name = request.getParameter("name"); 28 String key = request.getParameter("key"); 29 //返回驗證結果 30 return userService.isLoginOk(name,key) ? "YES" : "NO"; 31 } 32 }
- isLoginOk(登錄函數)

1 public boolean isLoginOk(String username, String password){ 2 //這里使用了最簡單粗暴的方法,獲取全部用戶信息后再逐個進行對比 3 List<UserEntity> list = getAll(); 4 for (UserEntity arr:list) { 5 if(username.equals(arr.getUserName())&&password.equals(arr.getUserKey())) 6 return true; 7 } 8 return false; 9 }
這個登錄驗證函數是在UserDaoImpl里實現的(具體代碼見本系列第二篇),供Service調用,最終由LoginController接受客戶端的請求並提供相應功能。這里對於驗證結果的返回沒有做復雜的處理,只是簡單地返回了字符串“YES”或“NO”,供客戶端進行判斷。運行效果如下(用戶名:fffvv,密碼:122211,為本系列第二篇中新增的用戶):
密碼錯誤示意圖
密碼正確示意圖
好了,至此一個簡單的登錄模塊已經完成了。你也可以嘗試使用安卓的SharedPerferences對用戶的信息進行保存,避免每次都需要用戶登錄。本期的介紹到這里也就差不多了。如果你對代碼中的某些部分有疑問,歡迎在評論區里指出,我會在空閑時間盡快進行回復。
—————————我———是———分———割———線—————————
廢話來啦!
本來是要打算周五正常更新的,不過上午突然接到了個老師的通知,大概內容是我們組馬上要對方案設計進行線上答辯了,PPT也要進行改動。想了想這周還有一個計網實驗報告沒寫,最近打卡變撈也想得到提升,就早早把這篇文章趕出來了,本周五的更新就算是提前了吧,昨天真不該毒奶的。。。