SAPUI5 (39) - 直接提交 HTTP 请求实现 CRUD

2024-02-05 13:48

本文主要是介绍SAPUI5 (39) - 直接提交 HTTP 请求实现 CRUD,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

OpenUI5 作为一种客户端的 UI 技术,自身并不直接与后端的服务器或者数据库交互。客户端只是提交 HTTP request,不管是 ODatacreate / update / delete 等方法,还是单向绑定或双向绑定时的 submitChanges 方法,都是对 HTTP Request 的一种封装。网络上有文章介绍 OpenUI5 中如何提交 HTTP request,或者使用 Ajax call 提交 HTTP request。这些方法对于服务器不提供 OData service 的场合有其实用价值。

本文介绍如何在 OpenUI5 中向后端提交 HTTP Request,实现 CRUD 的方法。代码基于第 38 篇的代码进行修改。

基本上,View 的部分没有变化,主要变化集中在 Controller (App.controller.js 文件)中。

Edit

editEmployee: function() {var oView = this.getView();var oChangedData = {EmpId: oView.byId("EmpId").getValue(),EmpName: oView.byId("EmpName").getValue(),EmpAddr: oView.byId("EmpAddr").getValue()};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "GET",headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/atom+xml","DataServiceVersion": "2.0","X-CSRF-Token": "Fetch"}},function(data, response) {var oHeaders = {"x-csrf-token": response.headers["x-csrf-token"],"Accept": "application/json"};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "PUT",headers: oHeaders,data: oChangedData},// successfunction(oData, oRequest) {sap.m.MessageToast.show("Employee updated Successfully");oEmployeeModel.refresh(true);},// errorfunction(oError) {sap.m.MessageToast.show("Employee update Failed");});},function(err) {var request = err.request;var response = err.response;sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);});
}

代码说明:

  • 使用 oChangedData 对象表示修改过的数据,一共三个字段。

  • OData.request() 方法提交 HTTP 请求。这里比较 magical 的一点事情,就是 OData model 定义后,就存在全局 (global) 的 OData 对象。

  • serviceUrlonInit 事件中,从 manifest.json 文件获得:

onInit: function() {...// get service url from manifest.jsonvar config = this.getOwnerComponent().getManifest();sServiceUrl = config["sap.app"].dataSources.mainService.uri;...
}

Create

createEmployee: function() {var oView = this.getView();var oNewEntry = {EmpId: oView.byId("EmpId").getValue(),EmpName: oView.byId("EmpName").getValue(),EmpAddr: oView.byId("EmpAddr").getValue()};OData.request({requestUri: sServiceUrl + "EmployeeCollection",method: "GET",headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/atom+xml","DataServiceVersion": "2.0","X-CSRF-Token": "Fetch"}},function(data, response) {var oHeaders = {"x-csrf-token": response.headers["x-csrf-token"],"Accept": "application/json"};OData.request({requestUri: sServiceUrl + "EmployeeCollection",method: "POST",headers: oHeaders,data: oNewEntry},// successfunction(oData, oRequest) {sap.m.MessageToast.show("Employee Created Successfully");oEmployeeModel.refresh(true);},// errorfunction(oError) {sap.m.MessageToast.show("Employee Creation Failed");});},function(err) {var request = err.request;var response = err.response;sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);});
}

Delete

deleteEmployee: function() {var oView = this.getView();var oEntry = {EmpId: oView.byId("EmpId").getValue()};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "GET",headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/atom+xml","DataServiceVersion": "2.0","X-CSRF-Token": "Fetch"}},function(data, response) {var oHeaders = {"x-csrf-token": response.headers["x-csrf-token"],"Accept": "application/json"};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "DELETE",headers: oHeaders,data: oEntry},// successfunction(oData, oRequest) {sap.m.MessageToast.show("Employee deleted Successfully");window.location.reload(true);},// errorfunction(oError) {sap.m.MessageToast.show("Employee deletion Failed");});},function(err) {var request = err.request;var response = err.response;sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);});
}

Controller 完整代码

以下是 Controller 的完整代码。

sap.ui.define(["sap/ui/core/mvc/Controller"
], function(Controller) {"use strict";var oEmployeeDialog;var oEmployeeModel;var sServiceUrl;var sCurrentPath;var sCurrentEmp; // cureent employeereturn Controller.extend("zui5_odata_http_request.controller.App", {onInit: function() {oEmployeeModel = this.getOwnerComponent().getModel();// get service url from manifest.jsonvar config = this.getOwnerComponent().getManifest();sServiceUrl = config["sap.app"].dataSources.mainService.uri;oEmployeeModel.setUseBatch(false);this.getView().setModel(oEmployeeModel);oEmployeeDialog = this.buildDialog();},// Build employee dialogbuildDialog: function() {var oView = this.getView();var oEmpDialog = oView.byId("employeeDialog");if (!oEmpDialog) {oEmpDialog = sap.ui.xmlfragment(oView.getId(),"zui5_odata_http_request.view.EmployeeDialog");oView.addDependent(oEmpDialog);var oCancelButton = oView.byId("CancelButton");oCancelButton.attachPress(function() {oEmpDialog.close();});}return oEmpDialog;},onCreate: function() {var that = this;var oView = this.getView();oEmployeeDialog.open();// set form propertiesoEmployeeDialog.setTitle("Create Employee");oView.byId("EmpId").setEditable(true);oView.byId("SaveEdit").setVisible(false);oView.byId("SaveCreate").setVisible(true);// clear values of controlsoView.byId("EmpId").setValue("");oView.byId("EmpName").setValue("");oView.byId("EmpAddr").setValue("");oView.byId("SaveCreate").attachPress(function() {// commit creationthat.createEmployee();// close dialogif (oEmployeeDialog) {oEmployeeDialog.close();}});},onEdit: function() {var that = this;var oView = this.getView();// Set bindingif (sCurrentPath) {oEmployeeDialog.bindElement(sCurrentPath);} else {sap.m.MessageToast.show("No employee was selected.");return;}oEmployeeDialog.open();oEmployeeDialog.setTitle("Edit Employee");oView.byId("EmpId").setEditable(false);oView.byId("SaveEdit").setVisible(true);oView.byId("SaveCreate").setVisible(false);oView.byId("SaveEdit").attachPress(function() {that.editEmployee();// close dialogif (oEmployeeDialog) {oEmployeeDialog.close();}});},onDelete: function() {var that = this;if (!sCurrentPath) {sap.m.MessageToast.show("Now employee was selected.");return;}// Build dialogvar oDeleteDialog = new sap.m.Dialog();oDeleteDialog.setTitle("Delete Employee");oDeleteDialog.addContent(new sap.m.Label({text: "Are you sure to delete Employee " + sCurrentEmp + "?"}));oDeleteDialog.addButton(new sap.m.Button({text: "Confirm",press: function() {that.deleteEmployee();oDeleteDialog.close();}}));oDeleteDialog.open();},createEmployee: function() {var oView = this.getView();var oNewEntry = {EmpId: oView.byId("EmpId").getValue(),EmpName: oView.byId("EmpName").getValue(),EmpAddr: oView.byId("EmpAddr").getValue()};OData.request({requestUri: sServiceUrl + "EmployeeCollection",method: "GET",headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/atom+xml","DataServiceVersion": "2.0","X-CSRF-Token": "Fetch"}},function(data, response) {var oHeaders = {"x-csrf-token": response.headers["x-csrf-token"],"Accept": "application/json"};OData.request({requestUri: sServiceUrl + "EmployeeCollection",method: "POST",headers: oHeaders,data: oNewEntry},// successfunction(oData, oRequest) {sap.m.MessageToast.show("Employee Created Successfully");oEmployeeModel.refresh(true);},// errorfunction(oError) {sap.m.MessageToast.show("Employee Creation Failed");});},function(err) {var request = err.request;var response = err.response;sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);});},editEmployee: function() {var oView = this.getView();var oChangedData = {EmpId: oView.byId("EmpId").getValue(),EmpName: oView.byId("EmpName").getValue(),EmpAddr: oView.byId("EmpAddr").getValue()};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "GET",headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/atom+xml","DataServiceVersion": "2.0","X-CSRF-Token": "Fetch"}},function(data, response) {var oHeaders = {"x-csrf-token": response.headers["x-csrf-token"],"Accept": "application/json"};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "PUT",headers: oHeaders,data: oChangedData},// successfunction(oData, oRequest) {sap.m.MessageToast.show("Employee updated Successfully");oEmployeeModel.refresh(true);},// errorfunction(oError) {sap.m.MessageToast.show("Employee update Failed");});},function(err) {var request = err.request;var response = err.response;sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);});},deleteEmployee: function() {var oView = this.getView();var oEntry = {EmpId: oView.byId("EmpId").getValue()};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "GET",headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/atom+xml","DataServiceVersion": "2.0","X-CSRF-Token": "Fetch"}},function(data, response) {var oHeaders = {"x-csrf-token": response.headers["x-csrf-token"],"Accept": "application/json"};OData.request({requestUri: sServiceUrl + sCurrentPath.substr(1),method: "DELETE",headers: oHeaders,data: oEntry},// successfunction(oData, oRequest) {sap.m.MessageToast.show("Employee deleted Successfully");window.location.reload(true);},// errorfunction(oError) {sap.m.MessageToast.show("Employee deletion Failed");});},function(err) {var request = err.request;var response = err.response;sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);});},onItemPress: function(evt) {var context = evt.getSource().getBindingContext();sCurrentPath = context.getPath();sCurrentEmp = context.getProperty("EmpId");}});});

源代码

Github: sap_openui5_practice_projects

参考资料

Simple Exercise on OData and SAP UI5 Application for the basic CRUD Operation

这篇关于SAPUI5 (39) - 直接提交 HTTP 请求实现 CRUD的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/681106

相关文章

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM

OpenCV实现实时颜色检测的示例

《OpenCV实现实时颜色检测的示例》本文主要介绍了OpenCV实现实时颜色检测的示例,通过HSV色彩空间转换和色调范围判断实现红黄绿蓝颜色检测,包含视频捕捉、区域标记、颜色分析等功能,具有一定的参考... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1