实现Java提供后端服务,ARKTS来接收数据,并使用jdbc使用数据库。

首先Java提供后端服务:使用HuTool的包

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.16</version>
         </dependency>

代码分为三个结构:Main函数用于启动调用接口函数,接口函数负责启动web服务,并调用复杂的处理函数。

package org.example;

import org.example.Server.DataServer;

public class Main {
    public static void main(String[] args) {
        DataServer server = new DataServer(8899);
    }
}
package org.example.Server;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.server.SimpleServer;
public class DataServer {
    public DataServer(int port){
        SimpleServer server = HttpUtil.createServer(port);
        server.start();
        System.out.println("java web 服务已经启动......");

        // 启动用户服务
        UserServer userServer = new UserServer(server);
        userServer.startUserServer();

    }
}
package org.example.Server;
import cn.hutool.http.ContentType;
import cn.hutool.http.server.SimpleServer;

import java.nio.charset.Charset;
import java.util.Random;

public class UserServer {
    private SimpleServer  simpleServer;

    public UserServer(SimpleServer simpleServer){
        this.simpleServer = simpleServer;
    }
    public void startUserServer(){
        this.simpleServer.addAction("/query",(request, response)->{
            String[] datas = {"方山翠拥弘景路,江宁湖畔读书声",
                    "行知楼里传薪火,厚德兴业育俊英",
                    "金桂飘香秋色里,实验室中探物精",
                    "雪落金科银世界,梅开岁末映书灯",
                    "馆藏万卷融今古,智启千思向远行",
                    "青春作笔书华岁,不负金陵不负卿"};
            response.setCharset(Charset.forName("utf-8"));
            Random r = new Random();
            String result = datas[r.nextInt(datas.length)];
            response.write(result, ContentType.TEXT_PLAIN.toString());
        });
    }

}

arkTs端代码通过生命周期函数来循环访问

import { http } from "@kit.NetworkKit"

@Preview
@Component
export struct  OneView{
  private timerId: number = -1
  @State flag:boolean =false
  @State str:string = ''

aboutToAppear(): void {   
  this.timerId = setInterval(()=>{
    this.flag =false   //用于更新

    let httpRequest = http.createHttp()  //创建http套接字
    //设置访问对象和处理函数
    httpRequest.request("http://192.168.213.123:8899/query",(error,datas)=>{
      if(!error){
        let dataStr = datas.result;
        console.log("接收到数据:"+dataStr);
        this.str = dataStr as string;
        this.flag = true;
      }else{
        console.error("接收失败");
        this.flag = true
      }
    })
  },5000)  //定时

}
//回收生命周期函数
  aboutToDisappear() {   
    clearInterval(this.timerId)
  }

  build() {

    Column(){
      if(this.flag){
        Text(this.str)
          .width("100%")
          .textOverflow({overflow:TextOverflow.MARQUEE})
          .fontSize(20)
          .fontColor(Color.Red)
      }else{
        Text("正在请求数据,请稍后").fontSize(20)
      }
    }.width("100%").height("100%").justifyContent(FlexAlign.Center)


  }
}

onPageShow:是窗口的生命周期函数

aboutToAppear:是组件的生命周期函数

使用hutool的封装包来实现得到数据库数据的操作

同上基础操作,要额外启动一个逻辑函数,额外实现一个逻辑函数

导入依赖:

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

//实现通过前端传递的参数来查询数据库,查询数据库的操作是hutool包中封装的方法

  public void getUserServer(){
        this.simpleServer.addAction("/query/find",(request, response)->{
            String id = request.getParam("id");
            String sql = "select * from user where id = ?";
            try {
                List<Entity> result = Db.use().query(sql,id);
                Entity entity = result.get(0);
                USER user = new USER();
                user.id = entity.getInt("id");
                user.name = entity.getStr("name");
                user.age = entity.getInt("age");
                //返回数据,转化为json
                user = JSONUtil.toBean(JSONUtil.toJsonStr(user),USER.class);
                response.setCharset(StandardCharsets.UTF_8);
                response.write(JSONUtil.toJsonStr(user), ContentType.JSON.toString());


            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }

arkTs端来发起请求:

import { http } from "@kit.NetworkKit"
@Component
export struct  FourView{
  @State str : string = ''           //记录收到的数据
  @State inputValue : string = ''   //记录输入的数字
  build() {
    Column()
    {
      TextInput({
        placeholder: '请输入文本...', // 占位提示文字
        text: this.inputValue // 绑定输入框内容
      })
        .width('90%') // 宽度占父容器90%
        .height(48) // 输入框高度
        .backgroundColor('#f5f5f5') // 背景色
        .borderRadius(8) // 圆角
        .padding({ left: 16, right: 16 }) // 内边距
        // 输入内容变化时更新状态变量
        .onChange((value: string) => {
          this.inputValue = value;
        })
      Button("查询")
        .onClick(()=>{
          let httpRequest = http.createHttp()
          httpRequest.request("http://192.168.213.123:8899/query/find?id="+this.inputValue,(error,datas)=>{
            if(!error){
              let result = datas.result
              console.log("接收到数据:",result)
              this.str = result as string
            }
          })
        })

      Text(this.str).fontSize(30)

    }.width("100%").height("100%").justifyContent(FlexAlign.Center)
  }
}

json数据格式的解析。

IBestui集成:能够提供简单美观的ui组件

只需要在图中位置加入配置

示例:

import { IBestButton } from "@ibestservices/ibest-ui";
import { LengthMetrics } from "@kit.ArkUI";

@Entry
@Component
struct Index {
  build() {
    Flex({ wrap: FlexWrap.Wrap, space: {main: LengthMetrics.vp(12), cross: LengthMetrics.vp(12)} }) {
      IBestButton({
        text: '主要按钮',
        type: 'primary'
      })
      IBestButton({
        text: '成功按钮',
        type: 'success'
      })
      IBestButton({
        text: '默认按钮',
        type: 'default'
      })
      IBestButton({
        text: '危险按钮',
        type: 'danger'
      })
      IBestButton({
        text: '警告按钮',
        type: 'warning'
      })
    }
  }
}

示例2:生成数据表:

import { IBestTable, IBestTableColumn } from "@ibestservices/ibest-ui"
import { http } from "@kit.NetworkKit"

//使用IBest快速实现简单的表格
interface UserTableData{
  uid : number
  uname : string
  ubirthday : string
  usex : string
  uaddress : string
}

@Preview
@Component
export struct  OneView{
  @State tableId : string = "table"
  @State users:Array<UserTableData> =  []

aboutToAppear(): void {
    let httpRequest = http.createHttp()
    httpRequest.request("http://192.168.88.1:8899/query",(error,datas)=>{
      if(!error){
        let dataStr = datas.result;
        console.log("接收到数据:"+dataStr);
        this.users = JSON.parse(dataStr+"") as UserTableData[]
      }else{
        console.error("接收失败");
      }
  })
}
  build() {

    Column(){
      IBestTable({ tableId: this.tableId, data: this.users, stripe: true,fixHeight:"120%"}){
        IBestTableColumn({ tableId: this.tableId, title: "编号", prop: "uid", cellWidth: "10%" })
        IBestTableColumn({ tableId: this.tableId, title: "姓名", prop: "uname", cellWidth: "20%" })
        IBestTableColumn({ tableId: this.tableId, title: "出生年月", prop: "ubirthday",cellWidth: "30%" })
        IBestTableColumn({ tableId: this.tableId, title: "性别", prop: "usex",cellWidth: "20%" })
        IBestTableColumn({ tableId: this.tableId, title: "家庭地址", prop: "uaddress",cellWidth: "20%" })
      }
    }.width("100%").height("100%").justifyContent(FlexAlign.Center)
  }
}

效果:

当然还有其他的组件使用,IBest-UI 。可在官网查询。

在将ai集成到java中,这里使用的是基于hutool集成的deepseek。

首先在deepseek官网创建APIkey

https://platform.deepseek.com/usage

package org.example;

import cn.hutool.ai.AIUtil;
import cn.hutool.ai.ModelName;
import cn.hutool.ai.core.AIConfigBuilder;
import cn.hutool.ai.core.Message;
import cn.hutool.http.ContentType;
import cn.hutool.http.server.SimpleServer;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;


import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class DeepSeekService {
    private SimpleServer server;
    public DeepSeekService(SimpleServer simpleServer) {
        this.server = simpleServer;
    }
    public void talkDeepSeek(){
        this.server.addAction("/deepseekservice", (request, response) -> {
            System.out.println("talkDeepSeek  is   deepseekservice  start...");
            String  qu = request.getParam("qu");
            System.out.println("-->"+qu);
            List<Message> messages = new ArrayList<Message>();
            messages.add(new Message("user",qu));

            String chat = AIUtil.chat(new AIConfigBuilder(ModelName.DEEPSEEK.getValue())
                    .setApiKey("sk-69b15f3d87654cc7a89bb51564c60b4f").build(), messages);

            JSONObject jsonObject  =  new JSONObject(chat);
            JSONArray jsonArray = jsonObject.getJSONArray("choices");
            String  str = jsonArray.getJSONObject(0).getJSONObject("message").getStr("content");

            System.out.println(str);

            response.setCharset(Charset.forName("UTF-8"));

            response.write(str, ContentType.TEXT_PLAIN.toString());

            System.out.println(chat);

        });
    }
}

步骤:

提供构建函数得到web服务

使用函数addAction来创建web接口和执行逻辑

qu是规定的参数名,通过getParam得到前端的问题

Message 是 Hutool 封装的对话消息类,构造方法第一个参数是「角色」(user 代表用户,assistant 代表 AI 助手),第二个参数是「消息内容」(即客户端传入的 qu)

JSON数据序列号

发送到前端。

使用ApacheECharts报表:

Examples - Apache ECharts  ECharts官网

代码支持JavaScript和TypeScript

以JavaScript为例,使用思想是:做一个html页面,页面中只有图表,然后用web窗口组件显示在页面中:
html页面:使用的js来得到后端数据

import { http } from "@kit.NetworkKit";
import { webview } from "@kit.ArkWeb";

interface Sexs{
  sex:string
  Number : number
}

@Component
export struct  ThreeView{

  private controller : webview.WebviewController = new webview.WebviewController()

  @State datas : Array<Sexs> = []
  @State flag :boolean = false


  aboutToAppear(){
    setTimeout(()=>{
      let httpRequest = http.createHttp()
      httpRequest.request("http://192.168.88.1:8899/query/SexNumber",(error,datas)=>{
        if(!error){
          let dataStr = datas.result
          console.log("得到报表数据:"+dataStr)
          this.datas = JSON.parse(dataStr+"") as Array<Sexs>
          this.flag = true
        }
     })
    },)
  }

  build() {
    Column(){
      if(this.flag){
        Web({src:$rawfile("demo1.html"),controller:this.controller}).width("100%").height("50%")
      }else{
        Text("未获得数据")
      }
    }
  }
}

在ArkTs中引用
rawfile:存放初始资源

import { webview } from "@kit.ArkWeb";


@Component
export struct  ThreeView{

  private controller : webview.WebviewController = new webview.WebviewController()

  build() {
    Column(){
     Web({src:$rawfile("demo1.html"),controller:this.controller}).width("100%").height("50%")

    }
  }
}

后端:

发送JSON数据:

 public void getSex(){

        this.simpleServer.addAction("/query/SexNumber",(request, response)->{
            // 1. 必须允许所有来源
            response.addHeader("Access-Control-Allow-Origin", "*");

            // 2. 必须允许所有方法
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

            // 3. 必须允许所有头
            response.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

            // 4. 必须处理 OPTIONS 预检请求
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                // 替换为对应框架的状态码设置方法
                response.setHeader("Status", "200 OK");
                response.setContentType("application/json");
                response.write("{}");
                return;
            }

            String sql = "select usex,count(*) from user  group by usex";
            try {
                List<Entity> result = Db.use().query(sql);
                ArrayList<PieData> users = new ArrayList<>();
                for (Entity entity : result) {
                    PieData user = new PieData();
                    user.setCn(entity.getStr("usex"));
                    user.setEn(entity.getInt("count(*)"));
                    users.add(user);
                }
                //返回数据,转化为json
                response.write(JSONUtil.toJsonStr(users), ContentType.JSON.toString());
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐