JavaFx入门4 -对JavaFx入门3的客户端发送数据处理

上一篇 JavaFx入门3 —使用Spring boot开发一个微服务作为后台数据接收处理

上一篇的数据请求处理 使用的是HttpClientUtils发送get请求到后端

 //请求网络数据
    private void requestNetData(String v) {
        //runAsync 不支持返回值
        CompletableFuture<Void> future =
                CompletableFuture.runAsync(() -> {
                    System.out.println("线程已经开始运行!!");
                    //请求网络数据
            //http://localhost:8026/doGet?id=aa&name=bb
             //传入的是url
              try {
                 HttpClientUtils.doGet("http://localhost:8029/doGet?id=aa&name=bb", ResponseType.String);
            } catch (Exception e) {
                e.printStackTrace();
            }
              //更新ui 传入接收的数据
                    updateUi(v);
                });

    }

    //更新ui
    private void updateUi(String arg) {
          
        Platform.runLater(() -> {
            //先清空
            gridPane.getChildren().clear();
           
            //根据请求到的数据生成控件
            GridPane pane = new GridPane();
            pane.getChildren().add(0,new Text(""));
            List<GridPane> lists = new ArrayList<>();

            //更新ui  添加到GridPane
            GridPaneUtils.setNodeToPane(gridPane,lists);

        });
    }

修改上面 先用模拟数据

//更新ui
    private void updateUi(String arg) {
        Platform.runLater(() -> {
            //先清空
            gridPane.getChildren().clear();

            //模拟网络数据请求
            List<Student> getData = new ArrayList<>();
            Student stu0 = new Student();
            stu0.setId("101"); stu0.setName("曾华"); stu0.setSex("男"); stu0.setBirthday(new Date());
            stu0.setsClass("class 1");
            getData.add(stu0);
            getData.add(stu0);
            getData.add(stu0);
            getData.add(stu0);
            //根据请求到的数据生成控件
            List<GridPane> lists = new ArrayList<>();
            GridPane pane = new GridPane();
            pane.setVgap(20);
            pane.setHgap(80);
            pane.addRow(0,new Text("学号"),new Text("姓名"),new Text("性别"),new Text("出生日期"),new Text("班级名称"));
            for (int i = 0 ; i< getData.size() ; i++){
                Student data = getData.get(i);
                //Date转 字符串日期 1977-09-01
                SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
                String dateStr=sdf.format(data.getBirthday());
                pane.addRow(i+1,new Text(data.getId()),new Text(data.getName()),
                        new Text(data.getSex()),new Text(dateStr),new Text(data.getsClass()));
            }
            lists.add(pane);
            //更新ui  添加到GridPane
            GridPaneUtils.setNodeToPane(gridPane,lists);

        });
    }

运行起来是这样的
JavaFx入门4 -对JavaFx入门3的客户端发送数据处理_第1张图片

继续回看 先解决后端接收客户端的json数据

原先后端的Controller对doGet请求处理是这样的

 @GetMapping("/doGet")
    public String doGetTest(@RequestParam(value = "id",required = false) String id,
                            @RequestParam(value = "name",required = false)String name){
        return "doGet Test";
    }

如果是多个参数,就要写多个@RequestParam(value = “id”,required = false) String id,很明显不方便,使用下面 @RequestBody 注解用于接收json数据。将这段代码添加到之前的Controller里面

// @RequestBody 根据json数据转换成对应的Object
    @PostMapping("/json")
    public void jsonTest(@RequestBody Student student, HttpServletResponse response){
        System.out.print(student.toString());
        try {
            PrintWriter writer = response.getWriter();
            String jsonStr = JSON.toJSONString(student);
            writer.write(jsonStr);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这是使用HttpClient发送json数据

HttpClient发送Json数据到指定接口

/**
     * post发送json数据
     * @param url
     * @param param
     * @return
     */
    private static String doPost(String url, JSONObject param) {
        HttpPost httpPost = null;
        String result = null;
        try {
            HttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            if (param != null) {
                StringEntity se = new StringEntity(param.toString(), "utf-8");
                httpPost.setEntity(se); // post方法中,加入json数据
                httpPost.setHeader("Content-Type", "application/json");
            }
            
            HttpResponse response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
            
        } catch (Exception ex) {
            logger.error("发送到接口出错", ex);
        }
        return result;
    }

确保Spring Boot微服务正常运行,这里有个Studen实体类,测试一下

public static void main(String[] args) {
        Student stu = new Student();
        stu.setId("1234");
        stu.setName("zs");
        //实体类转json字符串
        String str1 = JSON.toJSONString(stu);
        //josn转JSONObject
        JSONObject jsonObject = (JSONObject) JSON.parse(str1);
        String res = doPost("http://localhost:8029/json", jsonObject);
        System.out.println(res);
    }

控制台打印 SpringBoot正常接收了HttpClient的post发送的json数据格式请求
在这里插入图片描述

我们需要对发送的数据进行处理然后返回结果给客户端

方案1 服务端进一步使用MySQL数据库进行数据CRUD操作

MySQL安装步骤

新建一个表

DROP TABLE IF EXISTS student;
create table student(
	stuNu varchar(20) primary key,
	stuName varchar(20) not null,
	stuSex varchar(20) not null,
	stuBirthday datetime,
	stuClass varchar(20)
	);

插入数据
JavaFx入门4 -对JavaFx入门3的客户端发送数据处理_第2张图片
查询一下
JavaFx入门4 -对JavaFx入门3的客户端发送数据处理_第3张图片
这里使用MVC模式写一个查询数据库的接口

StuTestService

package com.rweb.service;

import com.rweb.model.Student;

import java.util.List;

public interface StuTestService {
    List<Student> getAllStu();
}

StuTestServiceImpl

package com.rweb.service.impl;

import com.rweb.dao.StuTestDao;
import com.rweb.model.Student;
import com.rweb.service.StuTestService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("StuTestService")
public class StuTestServiceImpl implements StuTestService {
    @Resource
    private StuTestDao stuTestDao;

    @Override
    public List<Student> getAllStu() {
        return stuTestDao.getAllStu();
    }
}

StuTestDao

package com.rweb.dao;

import com.rweb.model.Student;
import org.springframework.stereotype.Repository;

import java.util.List;

//在每个mapper接口上添加@Repository注解
@Repository
public interface StuTestDao {

    List<Student> getAllStu();
}

这里使用了MyBatis,这是基于xml的Mapper文件

<?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.rweb.dao.StuTestDao">
    <!--格式:数据库字段 as 模型字段-->
    <sql id="Base_Column_List">
    stuNu as id,stuName as name,
    stuSex as sex,stuBirthday as birthday,
    stuClass as sClass
  </sql>

    <!-- 获取所有数据 -->
    <select id="getAllStu" resultType="com.rweb.model.Student">
        select
        <include refid="Base_Column_List" />
        from student
    </select>

</mapper>

StuTestController 测试

package com.rweb.controller;

import com.rweb.model.Student;
import com.rweb.service.StuTestService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller
public class StuTestController {

    @Resource
    private StuTestService stuTestService;

    @ResponseBody
    @RequestMapping("jsonData")
    public String jsonDataTest() {
        if (stuTestService.getAllStu() != null){
            List<Student> studentList= stuTestService.getAllStu();
            //List转json
            System.out.println(JSON.toJSONString(studentList));

            //json转jsonArray
            JSONArray jsonArrays =JSON.parseArray(JSON.toJSONString(studentList));

            List<Student> myList=new ArrayList<>();
            //JSONArray转List
            for(int i=0;i<jsonArrays.size();i++){

                Student student3=JSON.toJavaObject(jsonArrays.getJSONObject(i), Student.class);
                myList.add(student3);
            }
            for(Student stu:myList){
                System.out.println(stu);
            }

            return "OK";
        }else {
            return "null";
        }
    }

}

测试一下
在这里插入图片描述
控制台成功打印
JavaFx入门4 -对JavaFx入门3的客户端发送数据处理_第4张图片
StuTestController修改如下

@ResponseBody
    @RequestMapping("jsonData")
    public void jsonDataTest(HttpServletResponse response) {
        if (stuTestService.getAllStu() != null){
            List<Student> studentList= stuTestService.getAllStu();
            //List转json
            System.out.println(JSON.toJSONString(studentList));
            try {
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                response.setCharacterEncoding("utf-8");
                //response.setContentType("text/html; charset=utf-8");
                String jsonStr = JSON.toJSONString(studentList);
                writer.write(jsonStr);
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else {

        }
    }

客户端修改

//更新ui
private void updateUi(String arg) {
    Platform.runLater(() -> {
        //先清空
        gridPane.getChildren().clear();

        //模拟网络数据请求
        Student stu = new Student();
        stu.setId("1234");
        stu.setName("zs");
        String str1 = JSON.toJSONString(stu);
        JSONObject jsonObject = (JSONObject) JSON.parse(str1);
        //这里jsonObject暂时没多大用处
        String jsonData = doPost("http://localhost:8021/jsonData", jsonObject);
         //json转jsonArray
        JSONArray jsonArrays =JSON.parseArray(jsonData);

        List<Student> getData=new ArrayList<>();
        //JSONArray转List
        for(int i=0;i<jsonArrays.size();i++){
            Student student3=JSON.toJavaObject(jsonArrays.getJSONObject(i), Student.class);
            getData.add(student3);
        }
        for(Student obj:getData){
            System.out.println(obj);
        }


        //根据请求到的数据生成控件
        List<GridPane> lists = new ArrayList<>();
        GridPane pane = new GridPane();
        pane.setVgap(20);
        pane.setHgap(80);
        pane.addRow(0,new Text("学号"),new Text("姓名"),new Text("性别"),new Text("出生日期"),new Text("班级名称"));
        for (int i = 0 ; i< getData.size() ; i++){
            Student data = getData.get(i);
            //Date转 字符串日期 1977-09-01
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
            String dateStr=sdf.format(data.getBirthday());
            pane.addRow(i+1,new Text(data.getId()),new Text(data.getName()),
                    new Text(data.getSex()),new Text(dateStr),new Text(data.getsClass()));
        }
        lists.add(pane);
        //更新ui  添加到GridPane
        GridPaneUtils.setNodeToPane(gridPane,lists);

    });
}

成功接收服务端返回的json并解析数据
JavaFx入门4 -对JavaFx入门3的客户端发送数据处理_第5张图片
更多搜索、删除等操作待更新

方案2 客户端自己处理

本质读取本地txt文本文件
JavaFx入门5 - 一个小工具的实现

你可能感兴趣的:(JavaFX8,Java全栈开发,MySQL)