1.Eclipse环境配置及组件安装

 UI5-学习篇-1-Eclipse开发工具及环境搭建

2.创建项目

 

 

  

3.设置代理映射

 打开WebContent->WEB-INF->web.xml文件,设置代理地址: 

    <servlet>
        <servlet-name>SimpleProxyServlet</servlet-name>
        <servlet-class>com.sap.ui5.proxy.SimpleProxyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SimpleProxyServlet</servlet-name>
        <url-pattern>/proxy/*</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>com.sap.ui5.proxy.REMOTE_LOCATION</param-name>
        <param-value>http://XXX.XXXXX.com:8000</param-value>
    </context-param>

4.WebContent文件设置

 在WebContent文件夹下创建如下文件夹:

 controller:JavaScript应用层逻辑控制

 css:样式设置

 i18n:多语言设置

 localService:元数据文件

 model:数据层

 view:视图展现层

 

5.创建View及Controller

 选择view文件夹,创建view视图文件

 view -右键 New - other- 选择SAPUI5 Application Development - View

 

 

 

 视图设计目前有四种类型:JavaScript,XML,JSON,HTML,根据个人习惯进行选择,目前官网实例大多采用XML格式去设计,可以多了解XML。

 创建完成后,View文件夹会生成两个文件:MAT.controller.js    /  MAT.view.xml

 将MAT.controller.js文件拖放到controller文件夹下面,如下所示:

  

 MAT.view视图代码如下:

 
<mvc:View 
    controllerName="zrico_ecp_ui.controller.MAT" 
    xmlns:html="http://www.w3.org/1999/xhtml" 
    xmlns:mvc="sap.ui.core.mvc"
    xmlns:core="sap.ui.core" 
    xmlns:form="sap.ui.layout.form"
    displayBlock="true" xmlns="sap.m">
    <App>
        <pages>
            <Page title="{i18n>app_header_title}" id="PG_SEARCH">
            <content>
                <Panel    
                    xmlns:html="http://www.w3.org/1999/xhtml" 
                    xmlns:mvc="sap.ui.core.mvc" 
                    xmlns="sap.m" 
                    id="__panel0" 
                    headerText="{i18n>app_panel_title}">
                    <content>
                    <form:Form 
                        xmlns:html="http://www.w3.org/1999/xhtml" 
                        xmlns:mvc="sap.ui.core.mvc" 
                        xmlns="sap.m" 
                        xmlns:sap.ui.layout.form="sap.ui.layout.form" 
                        editable="true" 
                        id="__form2">
                        <form:formContainers>
                            <form:FormContainer 
                                id="__container2">
                                <form:formElements>
                                    <form:FormElement 
                                        id="__element2" 
                                        label="{i18n>app_panel_lable_usrid}">
                                        <form:fields>
                                            <Input 
                                                id="productInput" 
                                                type="Text" 
                                                width="auto" 
                                                textFormatMode="KeyValue" 
                                                placeholder="Enter User ID..." 
                                                showSuggestion="true" 
                                                showValueHelp="true" 
                                                valueHelpRequest="handleValueHelp" 
                                                suggestionItems="{/ZUSERSet}" 
                                                suggestionItemSelected="suggestionItemSelected">
                                                <suggestionItems>
                                                    <core:ListItem key="{Usrid}" text="{Usrname}" additionalText="{Usrid}"/>
                                                </suggestionItems>
                                            </Input>
                                            <Button 
                                                xmlns:html="http://www.w3.org/1999/xhtml" 
                                                xmlns:mvc="sap.ui.core.mvc" 
                                                xmlns="sap.m" 
                                                width="auto" 
                                                type="button"
                                                id="app_panel_button_read" 
                                                icon="sap-icon://search" 
                                                text="{i18n>app_panel_button_search}" 
                                                press="onRead"/>
                                            
                                        </form:fields>
                                        
                                    </form:FormElement>
                                    
                                </form:formElements>
                                
                            </form:FormContainer>
                            
                        </form:formContainers>
                        <form:layout>
                            <form:ResponsiveGridLayout 
                                id="__layout2"/>
                        </form:layout>
                        </form:Form>
                </content>
                </Panel>
                <Table xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" noDataText="No data" id="idTable" items="{path:'/ZUSERSet'}">
                    <items>
                        <ColumnListItem type="Navigation" press="onItemPress">
                            <cells>
                                <Text text="{Usrid}"/>
                                <Text text="{Usrname}"/>
                                <Text text="{Usraddr}"/>
                            </cells>
                        </ColumnListItem>
                    </items>
                    <columns>
                        <Column id="__column0">
                            <header>
                                <Label id="lUsrid" text="{i18n>app_table_header_usrid}"/>
                            </header>
                        </Column>
                        <Column id="__column1">
                            <header>
                                <Label text="{i18n>app_table_header_usrname}" id="lUsrname"/>
                            </header>
                        </Column>
                        <Column id="__column2">
                            <header>
                                <Label text="{i18n>app_table_header_usraddr}" id="lUsraddr"/>
                            </header>
                        </Column>
                        </columns>
                    </Table>
            </content>
               <footer>
                    <Bar>
                        <contentRight>
                            <Button icon="sap-icon://create" text="Create" press="onCreate"/>
                            <Button icon="sap-icon://edit" text="Edit" press="onEdit"/>
                            <Button icon="sap-icon://delete" text="Delete" press="onDelete"/>
                        </contentRight>
                    </Bar>
                </footer>
            </Page>
        </pages>
    </App>
</mvc:View>
View Code

 MAT.controller代码如下(注意替换文件中user/password):

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    'sap/ui/model/Filter',
    "sap/ui/model/json/JSONModel"
], function(Controller,Filter,JSONModel) {
    "use strict";
    var oModel;
    var rModel;
    var oAjax;
    var aFilters;
    var sCurrentPath; // current path
    var sCurrentUsr;  // cureent user
    var sServiceUrl;
    
    return Controller.extend("zrico_ecp_ui.controller.MAT", {
        inputId: '',
        
        onInit: function() {
//              oModel = this.getOwnerComponent().getModel();           
//              oModel.setUseBatch(false);
//              this.getView().setModel(oModel);
            
                oModel = new sap.ui.model.odata.ODataModel("proxy/sap/opu/odata/sap/ZRICO_STRU_USR_SRV/",{
                json: true,
                user: "XXXX",
                password: "XXXXX"
            });
            
            oModel.setUseBatch(false);
            this.getView().setModel(oModel);
        },
        
        onRead:function(){
            var sInputValue = this.getView().byId("productInput").getSelectedKey();
            // define filters
            if ( sInputValue === ""){
            aFilters = [    new Filter("Usrid", 
                    sap.ui.model.FilterOperator.Contains,
                    sInputValue) ];
            }
            else{
            aFilters = [    new Filter("Usrid", 
                    sap.ui.model.FilterOperator.EQ,
                    sInputValue)];
            }    
    
            // get data using filter
            oModel.read("/ZUSERSet", {
                filters: aFilters,     
                success: function(oData, oResponse){
                    //window.console.log(oData);
                }
            });
            
            var oList = this.getView().byId("idTable");
            var oBinding = oList.getBinding("items");
            oBinding.filter(aFilters);
            
        },
        
        openDialog: function() {
            var oView = this.getView();
            // Open dialog
            var oUsrDialog = oView.byId("UsrDialog");
            if (!oUsrDialog) {
                oUsrDialog = sap.ui.xmlfragment(oView.getId(),
                    "zrico_ecp_ui.view.UsrDialog");
                oView.addDependent(oUsrDialog);
            }
            oUsrDialog.open();
            // Attach press event for CancelButton
            var oCancelButton = oView.byId("CancelButton");
            oCancelButton.attachPress(function() {
                oUsrDialog.close();
            });
        },
        
        // onCreate event
        onCreate: function() {
            sap.m.MessageToast.show("Create starting.");
            var oView = this.getView();
            this.openDialog();
            var oUsrDialog = oView.byId("UsrDialog");
            oUsrDialog.setTitle("Create User");
            oView.byId("Usrid").setEditable(true);
            oView.byId("SaveEdit").setVisible(false);
            oView.byId("SaveCreate").setVisible(true);
            // clear
            oView.byId("Usrid").setValue("");
            oView.byId("Usrname").setValue("");
            oView.byId("Usraddr").setValue("");
            // commit save
            oView.byId("SaveCreate").attachPress(function() {
                var oNewEntry = {
                    "Mandt": "300",
                    "Usrid": "",
                    "Usrname": "",
                    "Usraddr": ""
                };
                // populate value from form
                oNewEntry.Usrid   = oView.byId("Usrid").getValue();
                oNewEntry.Usrname = oView.byId("Usrname").getValue();
                oNewEntry.Usraddr = oView.byId("Usraddr").getValue();
                
                if(!oNewEntry.Usrid){
                    sap.m.MessageToast.show("Please input the value of Usrid");
                    return;
                }else{
                    // Commit creation operation
                    oModel.create("/ZUSERSet", oNewEntry, {
                        success: function() {
                            sap.m.MessageToast.show("Created successfully.");
                        },
                        error: function(oError) {
                            window.console.log("Error", oError);
                        }
                    });
                }

                // close dialog
                if (oUsrDialog) {
                    oUsrDialog.close();
                }
            });
        },
        
        //onEdit event
        onEdit: function() {
            // no Item was selected
            if (!sCurrentUsr) {
                sap.m.MessageToast.show("No Item was selected.");
                return;
            }
            var oView = this.getView();
            this.openDialog();
            var oUsrDialog = oView.byId("UsrDialog");
            oUsrDialog.setTitle("Edit User");
            oView.byId("Usrid").setEditable(false);
            oView.byId("SaveEdit").setVisible(true);
            oView.byId("SaveCreate").setVisible(false);
            // populate fields
            oView.byId("Usrid").setValue(oModel.getProperty(sCurrentPath + "/Usrid"));
            oView.byId("Usrname").setValue(oModel.getProperty(sCurrentPath + "/Usrname"));
            oView.byId("Usraddr").setValue(oModel.getProperty(sCurrentPath + "/Usraddr"));
            // Attach save event
            oView.byId("SaveEdit").attachPress(function() {
                var oChanges = {
                    "Mandt": "300",
                    "Usrid":"",
                    "Usrname": "",
                    "Usraddr": ""
                };
                // populate value from form
                oChanges.Usrid =  oView.byId("Usrid").getValue();
                oChanges.Usrname = oView.byId("Usrname").getValue();
                oChanges.Usraddr = oView.byId("Usraddr").getValue();
                // commit creation
                oModel.update(sCurrentPath, oChanges, {
                    success: function() {
                        sap.m.MessageToast.show("Changes were saved successfully.");
                    },
                    error: function(oError) {
                        window.console.log("Error", oError);
                    }
                });
                // close dialog
                if (oUsrDialog) {
                    oUsrDialog.close();
                }
            });
        },
        // onDelete event
        onDelete: function() {
            var that = this;
            // no Item was selected
            if (!sCurrentUsr) {
                sap.m.MessageToast.show("No Item was selected.");
                return;
            }
            var oDeleteDialog = new sap.m.Dialog();
            oDeleteDialog.setTitle("Deletion");
            var oText = new sap.m.Label({
                text: "Are you sure to delete UsrId [" + sCurrentUsr + "]?"
            });
            oDeleteDialog.addContent(oText);
            oDeleteDialog.addButton(
                new sap.m.Button({
                    text: "Confirm",
                    press: function() {
                        that.deleteUsr();
                        oDeleteDialog.close();
                    }
                })
            );
            oDeleteDialog.open();
        },
        // deletion operation
        deleteUsr: function() {
            oModel.remove(sCurrentPath, {
                success: function() {
                    sap.m.MessageToast.show("Deletion successful.");
                },
                error: function(oError) {
                    window.console.log("Error", oError);
                }
            });
        },

        onItemPress: function(evt) {
            var oContext = evt.getSource().getBindingContext();
            sCurrentPath = oContext.getPath();
            sCurrentUsr = oContext.getProperty("Usrname");
        },
        
        //Input usrid value help
        handleValueHelp : function (oEvent) {
            var sInputValue = oEvent.getSource().getValue();

            this.inputId = oEvent.getSource().getId();
            // create value help dialog
            if (!this._valueHelpDialog) {
                this._valueHelpDialog = sap.ui.xmlfragment(
                    "zrico_ecp_ui.view.InputUsridDialog",
                    this
                );
                this.getView().addDependent(this._valueHelpDialog);
            }

            // create a filter for the binding
            this._valueHelpDialog.getBinding("items").filter([new Filter(
                "Usrname",
                sap.ui.model.FilterOperator.Contains, sInputValue
            )]);

            // open value help dialog filtered by the input value
            this._valueHelpDialog.open(sInputValue);
        },
        
        _handleValueHelpSearch : function (evt) {
            var sValue = evt.getParameter("value");
            var oFilter = new Filter(
                "Usrname",
                sap.ui.model.FilterOperator.Contains, sValue
            );
            evt.getSource().getBinding("items").filter([oFilter]);
        },

        _handleValueHelpClose : function (evt) {
            var oSelectedItem = evt.getParameter("selectedItem");
            if (oSelectedItem) {
                var productInput = this.byId(this.inputId),
                    //oText = this.byId('selectedKey'),
                    sDescription = oSelectedItem.getDescription();

                productInput.setSelectedKey(sDescription);
                //oText.setText(sDescription);
            }
            evt.getSource().getBinding("items").filter([]);
        },
        
        suggestionItemSelected: function (evt) {
            var oItem = evt.getParameter('selectedItem'),
                //oText = this.byId('selectedKey'),
                sKey = oItem ? oItem.getKey() : '';
            //oText.setText(sKey);
        }
    });
});
View Code

 

 6.创建Fragment

 创建两个对话框:InputUsridDialog  / UsrDialog

 选中view视图,右键New ,File

 

 

 InputUsridDialog.fragment.xml代码部分:

 
<core:FragmentDefinition
    xmlns="sap.m"
    xmlns:core="sap.ui.core">
    <SelectDialog
        title="{i18n>inputusriddialog_header_title}"
        class="sapUiPopupWithPadding"
        items="{/ZUSERSet}"
        search="_handleValueHelpSearch"
        confirm="_handleValueHelpClose"
        cancel="_handleValueHelpClose">
        <StandardListItem
            title="{Usrid}{Usrname}"
            description="{Usrid}" />
    </SelectDialog>
</core:FragmentDefinition>
View Code

 UsrDialog.fragment.xml代码部分:

 
<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:f="sap.ui.layout.form">
    <Dialog id="UsrDialog" title="{i18n>usrdialog_header_title}">
        <f:SimpleForm>
            <Label text="{i18n>usrdialog_lable_usrid}"/>
            <Input id="Usrid" value="{Usrid}"/>
            <Label text="{i18n>usrdialog_lable_usrname}"/>
            <Input id="Usrname" value="{Usrname}"/>
            <Label text="{i18n>usrdialog_lable_usraddr}"/>
            <Input id="Usraddr" value="{Usraddr}"/>
        </f:SimpleForm>
        <Toolbar>
            <ToolbarSpacer/>
            <Button id="SaveCreate" text="Save"/>
            <Button id="SaveEdit" text="Save Edit"/>
            <Button id="CancelButton" text="Cancel"/>
        </Toolbar>
    </Dialog>
</core:FragmentDefinition>
View Code

7.多语言文件i18n

 i18n文件夹下创建文件i18n.properties

 选择文件夹i18n,右键New - File,创建文件名i18n.properties,如下图:

 

 i18n.properties内容如下:

  
app_header_title=用户信息查询
app_panel_title=查询条件
app_panel_lable_usrid=用户ID
app_panel_button_search=查询
app_table_header_usrid=用户ID
app_table_header_usrname=用户名称
app_table_header_usraddr=用户地址
usrdialog_header_title=用户信息维护 
usrdialog_lable_usrid=用户ID
usrdialog_lable_usrname=用户名称
usrdialog_lable_usraddr=用户地址
usrdialog_button_savecreate=保存
usrdialog_button_saveedit=保存修改
usrdialog_button_cancel=取消
inputusriddialog_header_title=用户ID选择
View Code

8.mainfest配置文件

 mainfest.json配置文件

 
{
    "_version": "1.7.0",
    "sap.app": {
        "id": "zrico_ecp_ui",
        "type": "application",
        "i18n": "i18n/i18n.properties",
        "applicationVersion": {
            "version": "1.0.0"
        },
        "title": "{{appTitle}}",
        "description": "{{appDescription}}",
        "sourceTemplate": {
            "id": "servicecatalog.connectivityComponent",
            "version": "0.0.0"
        },
        "dataSources": {
            "ZRICO_STRU_USR_SRV": {
                "uri": "/sap/opu/odata/sap/ZRICO_STRU_USR_SRV/",
                "type": "OData",
                "settings": {
                    "odataVersion": "2.0",
                    "localUri": "localService/metadata.xml"
                }
            },
            "ajaxUser":{
                "uri": "./model/ajaxinfo.json",
                "type": "JSON"
            }
        }
    },
    "sap.ui": {
        "technology": "UI5",
        "icons": {
            "icon": "",
            "favIcon": "",
            "phone": "",
            "phone@2": "",
            "tablet": "",
            "tablet@2": ""
        },
        "deviceTypes": {
            "desktop": true,
            "tablet": true,
            "phone": true
        },
        "supportedThemes": [
            "sap_hcb",
            "sap_belize"
        ]
    },
    "sap.ui5": {
        "rootView": {
            "viewName": "zrico_ecp_ui.view.MAT",
            "type": "XML"
        },
        "dependencies": {
            "minUI5Version": "1.30.00",
            "libs": {
                "sap.collaboration": {},
                "sap.m": {},
                "sap.ui.comp": {},
                "sap.ui.core": {},
                "sap.ui.layout": {},
                "sap.ushell": {},
                "sap.uxap": {}
            }
        },
        "contentDensities": {
            "compact": true,
            "cozy": true
        },
        "models": {
            "i18n": {
                "type": "sap.ui.model.resource.ResourceModel",
                "settings": {
                    "bundleName": "zrico_ecp_ui.i18n.i18n"
                }
            },
            "ajaxinfo": {
                "type": "sap.ui.model.json.JSONModel",
                "dataSource": "ajaxUser"
             },
            "": {
                "type": "sap.ui.model.odata.v2.ODataModel",
                "settings": {
                    "defaultOperationMode": "Server",
                    "defaultBindingMode": "OneWay",
                    "defaultCountMode": "Request"
                },
                "dataSource": "ZRICO_STRU_USR_SRV",
                "preload": true
            }
        },
        "resources": {
            "css": [
                {
                    "uri": "css/style.css"
                }
            ]
        }
    },
    "sap.platform.abap": {
        "uri": "/sap/bc/ui5_ui5/sap/zrico_ui5",
        "_version": "1.1.0"
    }
}
View Code

9.index.html启动页面 

 
<!DOCTYPE HTML>
<html>

    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta charset="UTF-8">

        <title>ZRICO_UI5_TEST</title>

        <script id="sap-ui-bootstrap"
            src="resources/sap-ui-core.js"
            data-sap-ui-libs="sap.m"
            data-sap-ui-theme="sap_belize"
            data-sap-ui-compatVersion="edge"
            data-sap-ui-resourceroots='{"zrico_ecp_ui": ""}'>
        </script>

        <link rel="stylesheet" type="text/css" href="css/style.css">

        <script>
            var serviceUrl = getServiceUrl("/mypath/myservice");
            function getServiceUrl(sServiceUrl) {
              if (window.location.hostname == "localhost") {
                  return "proxy" + sServiceUrl;
              } else {
                  return sServiceUrl;
              }
            }
        </script>        
        
        <script>
            sap.ui.getCore().attachInit(function() {
                new sap.m.Shell({
                    app: new sap.ui.core.ComponentContainer({
                        height : "100%",
                        name : "zrico_ecp_ui"
                    })
                }).placeAt("content");
            });
        </script>
    </head>

    <body class="sapUiBody" id="content">
    </body>

</html>
View Code

10.Tomcat执行测试

 选中项目名,右键Run As - Run on Server

 

 执行后: 

 创建:

  

 

 修改:

 

 

 

 

 删除:

 

 

 

11.Chrome浏览器调试

 打开浏览器chrome,输入路径:http://localhost:9090/zrico_ecp_ui/,然后快捷键F12打开调试控制台 

 

 

 

 

 

 

 

posted on 2019-03-06 16:26  ricoo  阅读(1109)  评论(0编辑  收藏  举报