使用鸿蒙制作简易应用

打印 上一主题 下一主题

主题 526|帖子 526|积分 1578

目录

写在前面
核心代码
前端(鸿蒙)
登录
LoginPage.ets
HttpUtil.ets
ReqUtil.ets
标签页
TabsPage.ets
首页
GridPage.ets
 MyGrid.ets
待办
TodoPage.ets
ItemComponent.ets
TaskDataModel.ets
 我的
ListPage.ets
MyList.ets
后端(使用Springboot) 
Entity
User.java
Controller
LoginController.java
 Mapper
UserMapper.java
UserMapper.xml
 Service
LoginService.java
LoginServiceImpl.java
Common
 AppFinal.java
ResponseBody.java
‘效果预览
登录页面
首页
待办
我的


写在前面

学习鸿蒙时尝试编写的一个简易应用,记录下实现的代码。

核心代码

前端(鸿蒙)

登录

LoginPage.ets

  1. import { getData } from '../utils/HttpUtil'
  2. import { loginUrl } from '../utils/ReqUtil'
  3. import router from '@ohos.router';
  4. @Entry
  5. @Component
  6. struct LoginPage{
  7.   @State message: string = 'Hello World'
  8.   loginData: any = {
  9.     username: '',
  10.     password: ''
  11.   }
  12.   build() {
  13.     Column(){
  14.       Image($r('app.media.logo')).width(90).margin({ top: 110 })
  15.       Text('登录界面').fontSize(30).fontWeight(800).margin({ top: 20 })
  16.       Text('登录账号以使用更多服务').fontColor('rgb(153,148,148)').margin( {top: 10 })
  17.       TextInput({ placeholder: '账号' }).margin({ top: 50 })
  18.         .onChange((value) => {
  19.           this.loginData.username = value;
  20.         })
  21.       TextInput({ placeholder: '密码' }).margin({ top: 15 })
  22.         .onChange((value) => {
  23.           this.loginData.password = value;
  24.         })
  25.       Row(){
  26.         Text("短信验证码登录").fontColor('rgb(0, 125, 254)')
  27.         Text("忘记密码").fontColor('rgb(0, 125, 254)')
  28.       }.width('100%').margin({ top: 10 }).justifyContent(FlexAlign.SpaceBetween)
  29.       Button('登录').width('100%').margin({ top: 80 })
  30.         .onClick(() =>{
  31.           //获取账号密码
  32.           console.log(JSON.stringify(this.loginData));
  33.           //发起请求
  34.           getData(loginUrl, this.loginData).then(res => {
  35.             if(res != -1) {
  36.               //登录成功
  37.               //将res里面的用户数据保存到缓存
  38.               //跳转到首页
  39.               router.pushUrl({url: 'pages/TabsPage'})
  40.             }
  41.           })
  42.         })
  43.       Text('注册账号').fontColor('rgb(0,125,254)').margin({ top: 10 })
  44.       Text('其他登录方式').fontColor('rgb(153,148,148)').margin({ top: 60 })
  45.       Row(){
  46.         Image($r('app.media.login_method1')).width(60)
  47.         Image($r('app.media.login_method2')).width(60)
  48.         Image($r('app.media.login_method3')).width(60)
  49.       }.width('100%').margin({ top: 15}).justifyContent(FlexAlign.SpaceEvenly)
  50.     }.width('100%').height('100%').padding(20)
  51.   }
  52. }
复制代码


HttpUtil.ets

  1. //弹窗模块
  2. import promptAction from '@ohos.promptAction';
  3. //1.引入http模块
  4. import http from '@ohos.net.http';
  5. //url常量
  6. const BASE_URL: string = 'http://localhost:8080'
  7. //封装函数,参数:url(请求地址),发送的数据:data
  8. export const getData = (url: string, data?: any) => {
  9.   //拼接请求接口
  10.   url = BASE_URL + url;
  11.   //2.创建请求
  12.   let httpRequest = http.createHttp();
  13.   //3.订阅请求头
  14.   httpRequest.on('headerReceive', (header) => {
  15.     console.log(JSON.stringify(header));
  16.   })
  17.   //4.发起请求
  18.   let promise = httpRequest.request(url, {
  19.     //请求方式
  20.     method: http.RequestMethod.POST,
  21.     //连接超时时间
  22.     connectTimeout: 20000,
  23.     //读取超时时间
  24.     readTimeout: 20000,
  25.     //添加请求头
  26.     header: {
  27.       'Content-type': 'application/json',
  28.       'Token': 'dwiaojdoiwjio32131'
  29.     },
  30.     //发送的数据
  31.     extraData: data
  32.   });
  33.   //5.处理相应内容
  34.   return promise.then((value: any) => {
  35.     //判断请求是否成功
  36.     if(value.responseCode == 200) {
  37.       //请求成功
  38.       //业务逻辑
  39.       let res = `${value.result}`;
  40.       let resData = JSON.parse(res);
  41.       //业务逻辑状态码:根据自己的后端返回值来判断
  42.       if(resData.status == 200) {
  43.         //console.log('200');
  44.         return resData;
  45.       } else {
  46.         //console.log('-1');
  47.         //提示用户
  48.         promptAction.showToast({
  49.           message: resData.message, //message为后端返回的信息
  50.           duration: 2000,
  51.           bottom: 400
  52.         })
  53.         return -1;
  54.       }
  55.       console.log(resData.status)
  56.       console.log(res);
  57.     }
  58.   })
  59. }
复制代码


ReqUtil.ets

  1. export const loginUrl: string = '/login/login'; //登录接口
复制代码


标签页

TabsPage.ets

  1. import { GridPage } from '../pages/GridPage'
  2. import { ListPage } from  '../pages/ListPage'
  3. import { TodoPage } from './TodoPage';
  4. @Entry
  5. @Component
  6. struct TabsPage{
  7.   @State message: string = 'Hello World'
  8.   //页签控制器
  9.   private tabController: TabsController = new TabsController();
  10.   //用户当前选择的页签下标
  11.   @State currentIndex: number = 0;
  12.   //页签按钮构造器
  13.   @Builder tabBuilder(title: string, index: number, selectImage: Resource, normalImage: Resource){
  14.     Column(){
  15.       //图片,如果当前下标和用户选择的下标一致:显示被选中的图片,否则:未被选中的图片
  16.       Image(this.currentIndex == index ? selectImage : normalImage).width(25)
  17.       //文字,如果当前下标和用户选择的下标一致:显示被选中的文字颜色,否则:未被选中的文字颜色
  18.       Text(title).fontColor(this.currentIndex == index ? 'rgb(1,124,254)' : 'rgb(200,200,200)')
  19.     }.width('100%').height(40)
  20.   }
  21.   build() {
  22.     Tabs({ barPosition: BarPosition.End, index:0, controller: this.tabController}) {
  23.       //首页
  24.       TabContent() {
  25.         /*Column() {
  26.         }.width('100%').height('100%').backgroundColor('rgb(81,198,224)')*/
  27.         GridPage();
  28.       }.tabBar(this.tabBuilder('首页', 0, $r('app.media.home_selected'), $r('app.media.home_normal')))
  29.       //待办
  30.       TabContent() {
  31.         /*Column() {
  32.         }.width('100%').height('100%').backgroundColor('rgb(147,228,75)')*/
  33.         TodoPage()
  34.       }.tabBar(this.tabBuilder('待办', 1, $r('app.media.discover_selected'), $r('app.media.discover_normal')))
  35.       //我的
  36.       TabContent() {
  37.         /*Column() {
  38.         }.width('100%').height('100%').backgroundColor('rgb(218,121,114)')*/
  39.         ListPage()
  40.       }.tabBar(this.tabBuilder('我的', 2, $r('app.media.mine_selected'), $r('app.media.mine_normal')))
  41.     }
  42.     .onChange((index) => {
  43.       //console.log(index + "")
  44.       //下标赋值给当前用户选择的下标
  45.       this.currentIndex = index;
  46.     })
  47.   }
  48. }
复制代码


首页

GridPage.ets

  1. import { MyGrid } from '../components/MyGrid';
  2. @Component
  3. export struct GridPage{
  4.   @State message: string = 'Hello World'
  5.   //定义数据
  6.   dataArray: object[] = [
  7.     {text:'我的最爱', image: $r('app.media.love')},
  8.     {text:'历史记录', image: $r('app.media.record')},
  9.     {text:'消息', image: $r('app.media.news')},
  10.     {text:'购物车', image: $r('app.media.shopping')},
  11.     {text:'我的目标', image: $r('app.media.target')},
  12.     {text:'圈子', image: $r('app.media.circle')},
  13.     {text:'收藏', image: $r('app.media.favorite')},
  14.     {text:'回收站', image: $r('app.media.storage')},
  15.   ]
  16.   build() {
  17.     Column() {
  18.       //标题
  19.       Text('首页').fontSize(40).fontWeight(FontWeight.Bold).width('100%')
  20.       //网格布局按钮
  21.       Grid(){
  22.         //循环渲染
  23.         ForEach(this.dataArray, (item) => {
  24.           GridItem(){
  25.               MyGrid({text: item.text, image: item.image})
  26.             }
  27.         })
  28.       }.columnsTemplate('1fr 1fr 1fr 1fr').rowsTemplate('1fr 1fr').columnsGap(20).rowsGap(20)
  29.       .backgroundColor(Color.White).height(150).borderRadius(30).margin({ top: 20 }).padding(15)
  30.     }.width('100%').height('100%').padding(20).backgroundColor('rgb(245,241,240)')
  31.   }
  32. }
复制代码


 MyGrid.ets

  1. @Component
  2. export struct MyGrid{
  3.   private text: string; //菜单名称
  4.   private image: Resource; //图片资源
  5.   build() {
  6.     Column(){
  7.       Image(this.image).width(30)
  8.       Text(this.text).fontSize(14).margin({ top: 5 })
  9.     }
  10.   }
  11. }
复制代码


待办

TodoPage.ets

  1. import  ItemComponent  from '../components/ItemComponent'
  2. import { TaskDataModel } from '../components/TaskDataModel'
  3. @Component
  4. export struct TodoPage {
  5.   private totalData: Array<string> = [] //待办列表所有的数据
  6.   aboutToAppear() { // 初始化数据
  7.     this.totalData = new TaskDataModel().getData()
  8.   }
  9.   build() {  //构建入口的UI界面
  10.     Column({ space : 6} ) {
  11.       Text('待办')
  12.         .fontSize(28)
  13.         .lineHeight(33)
  14.         .fontWeight(FontWeight.Bold)
  15.         .width('80%')
  16.         .margin({
  17.           top: 24,
  18.           bottom: 12
  19.         })
  20.         .textAlign(TextAlign.Start)
  21.       //循环渲染
  22.       ForEach(this.totalData, (item: string) =>{
  23.         ItemComponent({ task_content: item })
  24.       })
  25.     }
  26.     .width('100%')
  27.     .height('100%')
  28.     .backgroundColor('#F1F3F5')
  29.   }
  30. }
复制代码


ItemComponent.ets

  1. import  ItemComponent  from '../components/ItemComponent'
  2. import { TaskDataModel } from '../components/TaskDataModel'
  3. @Component
  4. export struct TodoPage {
  5.   private totalData: Array<string> = [] //待办列表所有的数据
  6.   aboutToAppear() { // 初始化数据
  7.     this.totalData = new TaskDataModel().getData()
  8.   }
  9.   build() {  //构建入口的UI界面
  10.     Column({ space : 6} ) {
  11.       Text('待办')
  12.         .fontSize(28)
  13.         .lineHeight(33)
  14.         .fontWeight(FontWeight.Bold)
  15.         .width('80%')
  16.         .margin({
  17.           top: 24,
  18.           bottom: 12
  19.         })
  20.         .textAlign(TextAlign.Start)
  21.       //循环渲染
  22.       ForEach(this.totalData, (item: string) =>{
  23.         ItemComponent({ task_content: item })
  24.       })
  25.     }
  26.     .width('100%')
  27.     .height('100%')
  28.     .backgroundColor('#F1F3F5')
  29.   }
  30. }
复制代码


TaskDataModel.ets

  1. export class TaskDataModel {
  2.   private tasks: Array<string> = [
  3.     "早起晨练",
  4.     "准备早餐",
  5.     "阅读名著",
  6.     "学习ArkTS",
  7.     "看剧放松"
  8.   ]
  9.   getData(): Array<string> {
  10.     return this.tasks
  11.   }
  12. }
复制代码


 我的

ListPage.ets

  1. import { MyList } from '../components/MyList'
  2. @Component
  3. export struct ListPage{
  4.   @State message: string = 'Hello World'
  5.   //数据数组
  6.   dataArray: object[] = [
  7.     {text:'推送通知', image: $r('app.media.news')},
  8.     {text:'数据管理', image: $r('app.media.data')},
  9.     {text:'菜单设置', image: $r('app.media.menu')},
  10.     {text:'关于', image: $r('app.media.about')},
  11.     {text:'清除缓存', image: $r('app.media.storage')},
  12.     {text:'隐私协议', image: $r('app.media.privacy')},
  13.   ]
  14.   build() {
  15.     Column() {
  16.       //标题
  17.       Text('我的').fontSize(40).fontWeight(FontWeight.Bold).width('100%')
  18.       //个人信息
  19.       Row() {
  20.         Image($r('app.media.account')).width(50).margin({ left: 20 })
  21.         Column(){
  22.           Text('李先生').fontSize(25).fontWeight(800)
  23.           Text('2471004754@qq.com').fontColor('rgb(120,120,120)')
  24.         }.alignItems(HorizontalAlign.Start).margin({ left: 15 }).height(60).justifyContent(FlexAlign.SpaceBetween)
  25.       }.width('100%').height(100).backgroundColor(Color.White).margin({ top: 40 }).borderRadius(30)
  26.       //菜单栏
  27.       Column() {
  28.         List({ space: 20 }) {
  29.           //循环渲染
  30.           ForEach(this.dataArray, (item) => {
  31.             ListItem(){
  32.               MyList({text: item.text, image: item.image});
  33.             }
  34.           })
  35.         }.divider({ strokeWidth : 2, color: 'rgb(238,238,238)'})
  36.       }.width('100%').height(400).backgroundColor(Color.White).borderRadius(30).margin({ top: 30 }).padding(20)
  37.     }.width('100%').height('100%').backgroundColor('rgb(245,241,240)').padding(20)
  38.   }
  39. }
复制代码


MyList.ets

  1. @Component
  2. export struct MyList{
  3.   private text: string; //菜单名称
  4.   private image: Resource; //菜单图片
  5.   build() {
  6.     Row(){
  7.       Row(){
  8.         //图片,菜单名称
  9.         Image(this.image).width(30)
  10.         Text(this.text).margin({ left: 10 }).fontSize(20)
  11.       }
  12.       //向右的箭头
  13.       Image($r('app.media.right_grey')).width(20)
  14.     }.width('100%').justifyContent(FlexAlign.SpaceBetween)
  15.   }
  16. }
复制代码


后端(使用Springboot) 

Entity

User.java

  1. package com.example.loginproject.entity;
  2. import lombok.Data;
  3. @Data
  4. public class User {
  5.     private Integer id;
  6.     private String username;
  7.     private String password;
  8. }
复制代码


Controller

LoginController.java

  1. package com.example.loginproject.controller;
  2. import com.example.loginproject.common.AppFinal;
  3. import com.example.loginproject.common.ResponseBody;
  4. import com.example.loginproject.entity.User;
  5. import com.example.loginproject.mapper.UserMapper;
  6. import com.example.loginproject.service.LoginService;
  7. import com.sun.net.httpserver.HttpServer;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.web.bind.annotation.RequestBody;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RequestParam;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import javax.annotation.Resource;
  14. import javax.servlet.http.HttpServlet;
  15. import javax.servlet.http.HttpServletRequest;
  16. import javax.servlet.http.HttpSession;
  17. @RestController
  18. @RequestMapping("/login")
  19. public class LoginController{
  20.     @Resource
  21.     private UserMapper userMapper;
  22.     @RequestMapping("/login")
  23.     public ResponseBody<User> login(@RequestBody User user,
  24.                                     HttpServletRequest request) {
  25.         User userInfo = userMapper.login(user.getUsername(), user.getPassword());
  26.         int status = 400;
  27.         String message = "用户或密码错误!";
  28.         if (userInfo != null && userInfo.getId() > 0) {
  29.             // 登录成功
  30.             status = 200;
  31.             message = "success";
  32.             // 将用户对象存储到 session 中
  33.             HttpSession session = request.getSession();
  34.             session.setAttribute(AppFinal.USERINFO_SESSION_KEY, userInfo);
  35.         }
  36.         return new ResponseBody<>(status, message, userInfo,-1);
  37.     }
  38. }
复制代码


 Mapper

UserMapper.java

  1. package com.example.loginproject.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.example.loginproject.entity.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. @Mapper
  6. public interface UserMapper extends BaseMapper<User> {
  7.     public User login(String username, String password);
  8. }
复制代码

UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.loginproject.mapper.UserMapper">
  4.     <select id="login" resultType="com.example.loginproject.entity.User">
  5.         select * from user where username=#{username} and password=#{password}
  6.     </select>
  7. </mapper>
复制代码

 Service

LoginService.java

  1. package com.example.loginproject.service;
  2. import com.baomidou.mybatisplus.extension.service.IService;
  3. import com.example.loginproject.entity.User;
  4. public interface LoginService extends IService<User> {
  5. }
复制代码


LoginServiceImpl.java

  1. package com.example.loginproject.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.example.loginproject.entity.User;
  4. import com.example.loginproject.mapper.UserMapper;
  5. import com.example.loginproject.service.LoginService;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {
  9. }
复制代码


Common

 AppFinal.java

  1. package com.example.loginproject.common;
  2. public class AppFinal {
  3.     // userinfo 存放到 session 中的 key
  4.     public static final String USERINFO_SESSION_KEY = "USERINFO_SESSION_KEY";
  5.     public static final String TERM_SESSION_KEY = "TERM_SESSION_KEY";
  6. }
复制代码

ResponseBody.java

  1. package com.example.loginproject.common;
  2. import lombok.Data;
  3. @Data
  4. public class ResponseBody<T> {
  5.     private int status;//code-200success-400failure
  6.     private String message;//msg-success-failure
  7.     private T data;//data
  8.     private Long total;//records count,无效用-1表示
  9.     public ResponseBody(int status, String message, T data,long total) {
  10.         this.status = status;
  11.         this.message = message;
  12.         this.data = data;
  13.         this.total = total;//records count
  14.     }
  15. }
复制代码


‘效果预览

登录页面


该页面只实现了登录功能,其他功能暂未实现。

登录成功后跳转至首页。


首页


仅实现了页面展示。


待办


点击后可以标记已办

再次点击重置



我的


 仅实现了页面展示。



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

河曲智叟

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表