HarmonyOS Next 實現登錄注冊頁面(ARKTS) 并使用Springboot作為后端提供接口

1. HarmonyOS next

ArkTS

ArkTS圍繞應用開發在 TypeScript (簡稱TS)生態基礎上做了進一步擴展,繼承了TS的所有特性,是TS的超集

ArkTS在TS的基礎上擴展了struct和很多的裝飾器以達到描述UI和狀態管理的目的

以下代碼是一個基于 HarmonyOS 的登錄頁面組件的示例代碼,主要實現了用戶登錄功能以及一些數據存儲和頁面跳轉的操作。下面我會逐步解釋每個部分并添加注釋:

2. 實例

3. 功能分區

1.1.HTTP獲取后臺接口數據,以下是示例
  async jwt(jwt: string) {try {const res = await this.httpUtil.request(`192.168.xxx.xxx/readers/userinfo`, {method: http.RequestMethod.GET,extraData: { no: jwt },});let data = JSON.parse(res.result.toString());return data;} catch (error) {throw error;}}
1.2 接口數據(作為測試,可以直接使用json):

2.生命周期函數的使用–AboutToAppear AboutToDisappear
  aboutToAppear() {let httpRequest = http.createHttp()this.httpUtil = httpRequest// todo 初始化上一次訪問時間this.getPreTime()// todo 初始化當前時間this.getLocalTimeToPreference()// todo 初始化本地數據庫的密碼和用戶名this.getUserInfo()}
3.APPStorage進程作為緩存,只能在應用運行時使用
4.DATAPreference 數據持久化,存于用戶本機
4. 分層結構

4.代碼演示

1. 導入模塊:

import router from '@ohos.router' // 導入路由模塊
import storage from '@ohos.data.storage' // 導入數據存儲模塊
import App from '@system.app' // 導入應用模塊
import Prompt from '@system.prompt' // 導入提示模塊
import http from '@ohos.net.http' // 導入網絡請求模塊
import { RouterInfo } from '../../Pojo/RouterInfo' // 導入自定義的 RouterInfo 類
import common from '@ohos.app.ability.common' // 導入通用模塊
import dataPreference from '@ohos.data.preferences' // 導入數據首選項模塊

2. 定義 `Login` 結構體:

@Entry
@Component
struct Login {
? // 定義狀態變量
? @State username: string = ""
? @State pwd: string = ""
? @State allow: boolean = false
? @State upload: boolean = true
? @State uploadTag: boolean = false
? @State lastLocalTime: string = ""
??
? // 其他屬性和方法...
}

3. 實例化 `RouterInfo` 對象和初始化方法:

RouterInfo是一個自定義的類

export class RouterInfo{name:stringurl:stringmessage:stringconstructor(name,url,message) {this.name=namethis.url=urlthis.message=message}
}Router = new RouterInfo("進入主頁", "pages/Books/Main", "主頁面")aboutToAppear() {
? // 初始化操作,包括創建 HTTP 請求對象、獲取上次訪問時間、初始化本地時間等
}

4. 頁面跳轉方法 `goTo()`:

goTo(Router: RouterInfo) {
? // 調用路由模塊進行頁面跳轉
}

5. 異步獲取用戶信息的方法 `jwt()`:

async jwt(jwt: string) {
? // 發起網絡請求獲取用戶信息
}

6. 存儲當前時間到用戶首選項方法 `getLocalTimeToPreference()`:

// 獲取當前時間并存入用戶首選項getLocalTimeToPreference(){const currentDate: Date = new Date();const currentYear: number = currentDate.getFullYear();const currentMonth: number = currentDate.getMonth() + 1; // 注意:月份從 0 開始,需要加 1const currentDay: number = currentDate.getDate();const currentHour: number = currentDate.getHours();const currentMinute: number = currentDate.getMinutes();const currentSecond: number = currentDate.getSeconds();const curTime = `北京時間:${currentYear}-${currentMonth}-${currentDay} ${currentHour}:${currentMinute}:${currentSecond}`;dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {preferences.put("curTime", curTime).then(_ => {preferences.flush();});}).catch((err: Error) => {console.error(err.message);});}

7. 獲取上一次訪問時間方法 `getPreTime()` 和關閉應用更新時間方法

 // 獲取上一次的時間--lastTimegetPreTime(){dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {if (!preferences.has("lastTime")) {console.log("數據并未能保存");} else {preferences.get("lastTime", 'null').then((value) => {this.last=value.toLocaleString()// AlertDialog.show({message:`上一次訪問時間:${this.last}`})console.log("數據為:" + value);}).catch(_ => {console.log("讀取失敗");});}});}// 關閉應用時將lastTime置換為curTime,并將curTime替換為空值closeAppAndUpdateTime(){dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {preferences.get("curTime", '').then((curTime) => {preferences.put("lastTime", curTime);preferences.put("curTime", '');preferences.flush();console.log("上一次時間已更新,當前時間已清空");}).catch((err: Error) => {console.error(err.message)});}).catch((err: Error) => {console.error(err.message);});}

8. 用戶登錄方法 `login()` 和相關輔助方法:

login() {
? // 用戶登錄邏輯,包括密碼驗證、令牌解析、存儲用戶信息等操作
}uploadUserInfo() {
? // 將用戶信息上傳到本地存儲
}getUserInfo() {
? // 獲取本地存儲的用戶信息
}

9. 構建頁面布局的方法 `build()`:

build() {
? // 構建頁面布局,包括輸入框、按鈕、復選框等組件
}

這段代碼實現了一個簡單的登錄頁面,涵蓋了用戶輸入、網絡請求、數據存儲等功能,并且使用 HarmonyOS 的一些模塊來實現這些功能。

5.全代碼

import router from '@ohos.router'
import storage from '@ohos.data.storage'
import App from '@system.app'
import Prompt from '@system.prompt'
import http from '@ohos.net.http'
import { RouterInfo } from '../../Pojo/RouterInfo'
import common from '@ohos.app.ability.common'
import dataPreference from '@ohos.data.preferences'
@Entry
@Component
struct Login {// todo 定義域@State username:string=""@State pwd:string=""@State allow:boolean = false@State upload:boolean = true@State uploadTag:boolean = false@State lastLocalTime:string=""httpUtil: http.HttpRequestcontext = getContext(this) as common.UIAbilityContext@State last:string=''Router = new RouterInfo("進入主頁","pages/Books/Main","主頁面")aboutToAppear() {let httpRequest = http.createHttp()this.httpUtil = httpRequest// todo 初始化上一次訪問時間this.getPreTime()// todo 初始化當前時間this.getLocalTimeToPreference()// todo 初始化本地數據庫的密碼和用戶名this.getUserInfo()}aboutToDisappear(){// todo 保存當前時間作為上一次的時間this.closeAppAndUpdateTime()}goTo(Router:RouterInfo){router.pushUrl({url: Router.url,params:{title:Router.message}},router.RouterMode.Single,err=> {if (err) {console.log("路由失敗"+err.code+':'+err.message)}})}async jwt(jwt: string) {try {const res = await this.httpUtil.request(`192.168.137.1/readers/userinfo`, {method: http.RequestMethod.GET,extraData: { no: jwt },});let data = JSON.parse(res.result.toString());return data;} catch (error) {throw error;}}// 獲取當前時間并存入用戶首選項getLocalTimeToPreference(){const currentDate: Date = new Date();const currentYear: number = currentDate.getFullYear();const currentMonth: number = currentDate.getMonth() + 1; // 注意:月份從 0 開始,需要加 1const currentDay: number = currentDate.getDate();const currentHour: number = currentDate.getHours();const currentMinute: number = currentDate.getMinutes();const currentSecond: number = currentDate.getSeconds();const curTime = `北京時間:${currentYear}-${currentMonth}-${currentDay} ${currentHour}:${currentMinute}:${currentSecond}`;dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {preferences.put("curTime", curTime).then(_ => {preferences.flush();});}).catch((err: Error) => {console.error(err.message);});}// 獲取上一次的時間--lastTimegetPreTime(){dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {if (!preferences.has("lastTime")) {console.log("數據并未能保存");} else {preferences.get("lastTime", 'null').then((value) => {this.last=value.toLocaleString()// AlertDialog.show({message:`上一次訪問時間:${this.last}`})console.log("數據為:" + value);}).catch(_ => {console.log("讀取失敗");});}});}// 關閉應用時將lastTime置換為curTime,并將curTime替換為空值closeAppAndUpdateTime(){dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {preferences.get("curTime", '').then((curTime) => {preferences.put("lastTime", curTime);preferences.put("curTime", '');preferences.flush();console.log("上一次時間已更新,當前時間已清空");}).catch((err: Error) => {console.error(err.message)});}).catch((err: Error) => {console.error(err.message);});}// todo 函數定義域async login() {if (this.username && this.pwd && this.allow) {try {const res = await this.httpUtil.request(`192.168.137.1/readers/login`, {method: http.RequestMethod.GET,extraData: { no: this.username, pwd: this.pwd },});let jsonResult = res.result.toString();let responseObject = JSON.parse(jsonResult);if (responseObject['code'] === 200) {// todo 解析令牌const data = await this.jwt(responseObject['data']);// todo 上下文 -- 存儲令牌AppStorage.SetOrCreate("info",data['data']['readerno'])// todo 是否將密碼存儲至本地if (this.upload===true) {this.uploadUserInfo()}// todo 跳轉this.goTo(this.Router)}} catch (error) {console.error(error);Prompt.showDialog({message: "登錄失敗",});}} else {if (!this.username || !this.pwd) {Prompt.showDialog({message: "請輸入用戶名和密碼",});} else if (!this.allow) {Prompt.showDialog({message: "請勾選允許登錄選項",});}}}uploadUserInfo(){// 用戶存儲信息到本地,使用用戶首選項dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {let user:{}={'username':this.username,'pwd':this.pwd}preferences.put("userInfo",JSON.stringify(user)).then(_ => {preferences.flush();});}).catch((err: Error) => {console.error(err.message);});}getUserInfo(){dataPreference.getPreferences(this.context, "myBookStore").then(preferences => {preferences.get("userInfo", '').then((userInfo) => {let user = JSON.parse(userInfo.toLocaleString())if (user) {this.uploadTag=truethis.username = user['username']this.pwd = user['pwd']}}).catch((err: Error) => {console.error(err.message)});}).catch((err: Error) => {console.error(err.message);});}build() {Column(){Column() {Text("掌上書店").fontColor('#096789').fontSize(70)this.displayLast("上一次訪問時間:"+this.last)if (this.uploadTag===true){this.displayLast("本地已經存儲密碼")}}.margin({ bottom: 100 }).height('50%').justifyContent(FlexAlign.Center)Column(){Row(){// 用戶名輸入框TextInput({ placeholder: this.username===''? "請輸入您的用戶名":this.username }).type(InputType.Normal).width('80%').height(50).placeholderColor(Color.Black).backgroundColor('#ffd3d7d3').borderRadius(10).margin({ bottom: 10}).onChange(val=>{this.username=valconsole.log(val)})}Row(){// 密碼輸入框TextInput({ placeholder: this.pwd===''?"請輸入您的密碼":this.pwd }).type(InputType.Password).width('80%').height(50).placeholderColor(Color.Black).backgroundColor('#ffd3d7d3').borderRadius(10).onChange(val=>{this.pwd=valconsole.log(val)})}Row(){Row(){Checkbox().onChange((val:boolean)=>{this.upload=valconsole.log('Checkbox2 change is'+val)})Text("將密碼存儲到本地")}.width('98%').padding({left:30}).height('40')}.margin({ bottom: 40 })Row(){//登錄按鈕Button("登錄").width(120).height(40).fontColor(Color.White).onClick(() => {this.login()}).backgroundColor('#ff5eb35b').margin({right:40}).borderStyle(BorderStyle.Dotted)//  注冊按鈕Button("注冊").width(120).height(40).fontColor(Color.White).onClick(() => {router.pushUrl({url: "pages/Second"})}).backgroundColor('#ff5eb35b')}.justifyContent(FlexAlign.SpaceEvenly)}.width("100%").height("30%")Row(){Checkbox().onChange((val:boolean)=>{this.allow=valconsole.log('Checkbox2 change is'+val)})Text("點擊代表同意相關使用條例與請求")}.width('90%').padding({left:30}).height('40')}.height('100%').width('100%').margin({bottom:20}).linearGradient({direction:GradientDirection.RightBottom,colors:[[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]]})}@Builder displayLast(message) {Row(){Text(message).fontColor("b#ffe7eae7")}.width("70%").height("40").backgroundColor("#ffe7eae7").borderRadius(20).padding({left:10}).margin({bottom:5})}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/64346.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/64346.shtml
英文地址,請注明出處:http://en.pswp.cn/web/64346.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Spring Boot教程之四十:使用 Jasypt 加密 Spring Boot 項目中的密碼

如何使用 Jasypt 加密 Spring Boot 項目中的密碼 在本文中,我們將學習如何加密 Spring Boot 應用程序配置文件(如 application.properties 或 application.yml)中的數據。在這些文件中,我們可以加密用戶名、密碼等。 您經常會遇到…

【Vue】如何在 Vue 3 中使用組合式 API 與 Vuex 進行狀態管理的詳細教程

如何在 Vue 3 中使用組合式 API 與 Vuex 進行狀態管理的詳細教程。 安裝 Vuex 首先,在你的 Vue 3 項目中安裝 Vuex。可以使用 npm 或 yarn: npm install vuexnext --save # or yarn add vuexnext創建 Store 在 Vue 3 中,你可以使用 creat…

七、隊列————相關概念詳解

隊列————相關概念詳解 前言一、隊列1.1 隊列是什么?1.2 隊列的類比 二、隊列的常用操作三、隊列的實現3.1 基于數組實現隊列3.1.1 基于環形數組實現的隊列3.1.2 基于動態數組實現的隊列 3.2 基于鏈表實現隊列 四、隊列的典型應用總結 前言 本篇文章,我們一起來…

基于 Ragflow 搭建知識庫-初步實踐

基于 Ragflow 搭建知識庫-初步實踐 一、簡介 Ragflow 是一個強大的工具,可用于構建知識庫,實現高效的知識檢索和查詢功能。本文介紹如何利用 Ragflow 搭建知識庫,包括環境準備、安裝步驟、配置過程以及基本使用方法。 二、環境準備 硬件要…

Pandas03

Pandas01 Pandas02 文章目錄 內容回顧1 排序和統計函數2 缺失值處理2.1 認識缺失值2.2 缺失值處理- 刪除2.3 缺失值處理- 填充非時序數據時序數據 3 Pandas數據類型3.1 數值類型和字符串類型之間的轉換3.2 日期時間類型3.3 日期時間索引 4 分組聚合4.1 分組聚合的API使用4.2 分…

springboot整合log4j2日志框架1

一 log4j基本知識 1.1 log4j的日志級別 Log4j定義了8個級別的log(除去OFF和ALL,可以說分為6個級別),優先級從低到高依次為:All,trace,debug,info,warn,err…

Spring源碼_05_IOC容器啟動細節

前面幾章,大致講了Spring的IOC容器的大致過程和原理,以及重要的容器和beanFactory的繼承關系,為后續這些細節挖掘提供一點理解基礎。掌握總體脈絡是必要的,接下來的每一章都是從總體脈絡中, 去研究之前沒看的一些重要…

WPF使用OpenCvSharp4

WPF使用OpenCvSharp4 創建項目安裝OpenCvSharp4 創建項目 安裝OpenCvSharp4 在解決方案資源管理器中,右鍵單擊項目名稱,選擇“管理 NuGet 包”。搜索并安裝以下包: OpenCvSharp4OpenCvSharp4.ExtensionsOpenCvSharp4.runtime.winSystem.Man…

leetcode 3083. 字符串及其反轉中是否存在同一子字符串 簡單

給你一個字符串 s ,請你判斷字符串 s 是否存在一個長度為 2 的子字符串,在其反轉后的字符串中也出現。 如果存在這樣的子字符串,返回 true;如果不存在,返回 false 。 示例 1: 輸入:s "…

TCP-UDP調試工具推薦:Socket通信測試教程(附詳細圖解)

前言 在網絡編程與應用開發中,調試始終是一項不可忽視的重要環節。尤其是在涉及TCP/IP、UDP等底層網絡通信協議時,如何確保數據能夠準確無誤地在不同節點間傳輸,是許多開發者關注的核心問題。 調試的難點不僅在于定位連接建立、數據流控制及…

Vue.js框架:在線教育系統的安全性與穩定性

2.1系統開發使用的關鍵技術 本系統在開發中選擇B/S框架進行設計,語言采用Java,數據庫采用Mysql,并在設計中加入VUE.js技術,本系統的運行環境為Idea。 2.2 VUE.js技術介紹 VUE.js是一個用來開發前臺界面的JavaScript框架&#xff0…

【新方法】通過清華鏡像源加速 PyTorch GPU 2.5安裝及 CUDA 版本選擇指南

下面詳細介紹所提到的兩條命令,它們的作用及如何在你的 Python 環境中加速 PyTorch 等庫的安裝。 1. 設置清華鏡像源 pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple這條命令的作用是將 pip (Python 的包管理工具&#xf…

【數據結構】單鏈表的使用

單鏈表的使用 1、基本概念2、鏈表的分類3、鏈表的基本操作a、單鏈表節點設計b、單鏈表初始化c、單鏈表增刪節點**節點頭插:****節點尾插:****新節點插入指定節點后:**節點刪除: d、單鏈表修改節點e、單鏈表遍歷,并打印…

虛幻引擎是什么?

Unreal Engine,是一款由Epic Games開發的游戲引擎。該引擎主要是為了開發第一人稱射擊游戲而設計,但現在已經被成功地應用于開發模擬游戲、恐怖游戲、角色扮演游戲等多種不同類型的游戲。虛幻引擎除了被用于開發游戲,現在也用于電影的虛擬制片…

Linux(Centos 7.6)yum源配置

yum是rpm包的管理工具,可以自動安裝、升級、刪除軟件包的功能,可以自動解決軟件包之間的依賴關系,使得用戶更方便軟件包的管理。要使用yum必須要進行配置,個人將其分為三類,本地yum源、局域網yum源、第三方yum源&#…

Linux上更新jar包里的某個class文件

目標:替換voice-1.0.jar里的TrackHandler.class文件 一.查詢jar包里TrackHandler.class所在的路徑 jar -tvf voice-1.0.jar |grep TrackHandler 二.解壓出TrackHandler.class文件 jar -xvf voice-1.0.jar BOOT-INF/classes/com/yf/rj/handler/TrackHandler.cla…

機器學習中回歸預測模型中常用四個評價指標MBE、MAE、RMSE、R2解釋

在機器學習中,評估模型性能時常用的四個指標包括平均絕對誤差(Mean Absolute Error, MAE)、均方誤差(Mean Squared Error, MSE)、均方根誤差(Root Mean Squared Error, RMSE)和決定系數&#xf…

基于SpringBoot的Jwt認證以及密碼aes加密解密技術

目錄 前言 1.SpringBoot項目的創建 2.相關技術 3.項目架構 4.項目關鍵代碼 5.項目最終的運行效果 ?編輯 6.PostMan測試接口結果 前言 學習了SpringBoot之后,才覺得SpringBoot真的很方便,相比傳統的SSH,SSM,SpringBo…

uniapp下載打開實現方案,支持安卓ios和h5,下載文件到指定目錄,安卓文件管理內可查看到

uniapp下載&打開實現方案,支持安卓ios和h5 Android: 1、申請本地存儲讀寫權限 2、創建文件夾(文件夾不存在即創建) 3、下載文件 ios: 1、下載文件 2、保存到本地,需要打開文件點擊儲存 使用方法&…

77、將adaface的mtcnn模型npy文件轉成atlas310p模型,并進行推理

基本思想:將adaface的mtcnn模型npy文件轉成atlas310p模型進行推理。同時比對結果 ubuntu@ubuntu:~$ git clone https://github.com/mk-minchul/AdaFace.git Cloning into AdaFace... remote: Enumerating objects: 236, done. remote: Counting objects: 100% (109/109), don…