跟我一起學extjs5(37--單個模組的設計[5取得模組列表資料]),extjs537--

來源:互聯網
上載者:User

跟我一起學extjs5(37--單個模組的設計[5取得模組列表資料]),extjs537--
跟我一起學extjs5(37--單個模組的設計[5取得模組列表資料])
        寫了幾個月,總算有點盼頭了,終於要從後台取得資料了。背景spring mvc 和 service 只能簡單的說說了,裡面加了幾十個類,有興趣的下載了源碼自己看。下面畫張通用的模組列表取資料的流程,這個流程是適用於所有的模組。我這個幕後處理程式也是對所有的模組進行統一處理,包括資料尋找,新增,修改,刪除都是相同的。



        畫圖不是強項,看得懂就行。        1、grid在渲染好後就會通過Stroe來取得資料;        2、Stroe會發送ajax請求至後台伺服器,spring mvc 會根據請求找到 ModuleController 中的相應取得資料的函數;        3、控制器中調用ModuleService中的函數取得資料;        4、Service再調用 ModuleDAO的函數從資料庫中取得資料,然後一級級的返回到Store中,再顯示在Grid之中。
        現在我們先做extjs5端的修改,原來的Store使用的是本機資料,現在要改成遠程調用的資料,
1、先修改model的產生函數ModelFactory.js。這個函數根據傳入的module的定義來產生model,主要產生的有fields屬性和proxy。還有一些以後要用到的函數,比如判斷此條記錄是否能修改、刪除等的函數。還有一個是取得本條記錄的標誌欄位的函數。

/** * 根據module的資料來產生模組的model */Ext.define('app.view.module.factory.ModelFactory', {statics : {getModelByModule : function(module) {var model = Ext.define('app.model.' + module.tf_moduleName, {extend : 'Ext.data.Model',module : module,idProperty : module.tf_primaryKey,nameFields : module.tf_nameFields,titleTpl : module.tf_titleTpl,titleTemplate : null,fields : this.getFields(module),proxy : {type : 'rest',batchActions : true,extraParams : {moduleName : module.tf_moduleName},api : {// 在這裡加rest/是因為在web.xml中// <url-pattern>/rest/*</url-pattern>這一句,spring會根據rest// 後面的參數去進行匹配read : 'rest/module/fetchdata.do',update : 'rest/module/update.do',create : 'rest/module/create.do',destroy : 'rest/module/remove.do'},actionMethods : {create : 'POST',read : 'GET',update : 'PUT',destroy : 'DELETE'},reader : {type : 'json',root : 'records',totalProperty : 'totalCount'},writer : {type : 'json',writeRecordId : true,writeAllFields : false// 沒有修改過的欄位不加入到update和delete的json中去},listeners : {exception : function(proxy, response, operation) {// 將出錯資訊加到proxy中去,傳遞到store的sync中顯示出錯資訊,顯示後將此屬性刪除proxy.errorInfo = Ext.decode(response.responseText, true);// 如果出錯資訊解析出錯,則加入一個預設的if (!proxy.errorInfo)proxy.errorInfo = {resultCode : -1,errorMessage : '未知原因:' + response.responseText}}}},getTitleTpl : function() {if (!this.titleTemplate) {if (this.titleTpl)this.titleTemplate = new Ext.Template(this.titleTpl);elsethis.titleTemplate = new Ext.Template('{' + this.nameFields + '}');}return this.titleTemplate.apply(this.getData())},// 此條記錄是否可以修改canEdit : function() {if (this.module.tf_hasAuditing && this.get('tf_auditinged'))return false;if (this.module.tf_hasApprove && this.get('tf_shNowCount') > 0)return false;return true;},// 此條記錄是否可以進行操作canOperate : function() {if (this.module.tf_hasAuditing && this.get('tf_auditinged'))return false;return true;},// 此條記錄是否可以刪除canDelete : function() {if (this.module.tf_hasAuditing && this.get('tf_auditinged'))return {canDelete : false,message : '【' + this.getTitleTpl() + '】已進行過審核,不允許進行刪除操作!'};if (this.module.tf_hasApprove && this.get('tf_shNowCount') > 0)return {canDelete : false,message : '【' + this.getTitleTpl() + '】正在審批或已經審批完成,不允許進行刪除操作!'};return true;},// 取得主索引值getIdValue : function() {return this.get(this.idProperty);},// 取得目前記錄的名字欄位getNameValue : function() {if (this.nameFields)return this.get(this.nameFields);elsereturn null;}});return model;},// String("String"), Boolean("Boolean"), Integer("Integer"),// Date("Date"), Double("Double"), Float("Float"); PercentgetFields : function(module) {var fields = [];for (var i in module.moduleFields) {var fd = module.moduleFields[i];var field = {name : fd.tf_fieldName,title : fd.tf_title,type : this.getTypeByStr(fd.tf_fieldType)};if (field.type == 'string') {field.useNull = true;field.serialize = this.convertToNull;}if (fd.tf_fieldType == 'Date') {field.dateWriteFormat = 'Y-m-d';field.dateReadFormat = 'Y-m-d';}if (fd.tf_fieldType == 'Datetime')field.dateReadFormat = 'Y-m-d H:i:s';field.tf_haveAttachment = fd.tf_haveAttachment;fields.push(field);}return fields;},getTypeByStr : function(str) {console.log(str);switch (str) {case 'String' :return 'string';case 'Boolean' :return 'boolean';case 'Integer' :return 'int';case 'Date' :return 'date';case 'Datetime' :return 'date';case 'Double' :case 'Float' :case 'Percent' :return 'float';default :return 'string';}},// 如果是Null 字元串,返回nullconvertToNull : function(v) {return v ? v : null;}}});

        2、在app.store的目錄下組建檔案GridStore.js。這是grid的Store的類的定義。
Ext.define('app.store.GridStore', {extend : 'Ext.data.Store',modulePanel : null,remoteSort : true,autoLoad : true,autoSync : true,leadingBufferZone : 100,buffered : false, // buffered=true可以無限下拉,但是刪除和新增,reload都有問題,暫時不用config : {extraParams : {},navigates : []// 導覽屬性選中的情況},constructor : function(param) {var me = this;this.pageSize = 20;this.extraParams = {};this.navigates = [];// 有建立時加進來的導航約束if (param.modulePanel.param) {var dnv = param.modulePanel.param.defaultNavigateValues;this.setDefaultNavigates(dnv);}// ///////////this.callParent(arguments);},listeners : {// 調用proxy進行ajax的時候,將參數加進 store.proxy中,在調用完成後,刪除掉所有的extraParams參數// 這樣model.proxy就可以多store,互相不干擾了beforeprefetch : function(store) {for (var i in store.extraParams)store.proxy.extraParams[i] = store.extraParams[i];},// buffered = true ,執行的是 prefetchprefetch : function(store, records, successful) {for (var i in store.extraParams)delete store.proxy.extraParams[i];},// buffered = false ,執行的是 loadbeforeload : function(store) {// console.log(store);for (var i in store.extraParams)store.proxy.extraParams[i] = store.extraParams[i];},load : function(store) {for (var i in store.extraParams)delete store.proxy.extraParams[i];}}});

        3、修改app.view.module.Module類,把store 和 model的產生方式都改一下。
initComponent : function() {console.log(this.moduleName + ' 正在建立');// 從MainModel中取得當前模組的定義資料,包括欄位和各種設定的資訊var mainmodel = this.up('app-main').getViewModel();this.module = mainmodel.getModuleDefine(this.moduleName);var viewmodel = new Ext.create('app.view.module.ModuleModel', {// 將該模組的定義資訊傳遞給本模組的viewModelmodule : this.module});this.setViewModel(viewmodel);this.glyph = this.getViewModel().get('tf_glyph'); // 由於上面的glyph的bind無效,因此需要在這裡加入glyph的設定this.model = app.view.module.factory.ModelFactory.getModelByModule(this.module);this.store = Ext.create('app.store.GridStore', {module : this.module,model : this.model,modulePanel : this});this.items = [{xtype : 'navigate', // 導航地區region : 'west',

        4、後台伺服器端在com.jfok.server.controller下加入ModuleController.java,這是spring mvc 的控制類。
package com.jfok.server.controller;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.hibernate.exception.ConstraintViolationException;import org.springframework.dao.DataAccessException;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import com.jfok.server.DAO.SystemBaseDAO;import com.jfok.server.DAO.module.ModuleDAO;import com.jfok.server.DAO.module.SqlModuleFilter;import com.jfok.server.common.ModuleServiceFunction;import com.jfok.server.hibernate.system._Module;import com.jfok.server.service.ApplicationService;import com.jfok.server.service.ModuleService;import com.jfok.shared.module.DataDeleteResponseInfo;import com.jfok.shared.module.DataFetchResponseInfo;import com.jfok.shared.module.DataInsertResponseInfo;import com.jfok.shared.module.DataUpdateResponseInfo;@Controller@RequestMapping(value = "/module")/** * 所有模組的的CRUD都是調用這個類的函數來完成的Controller裡面完成的 *  * @author jiangfeng * */public class ModuleController {@Resourceprivate SystemBaseDAO systemBaseDAO;@Resourceprivate ModuleService moduleService;@Resourceprivate ModuleDAO moduleDAO;private static final Log log = LogFactory.getLog(ModuleController.class);/** * 根據前台的請求取得資料 */@RequestMapping(value = "/fetchdata.do", method = RequestMethod.GET)public @ResponseBodyMap<String, Object> fetchData(String moduleName, Integer start, Integer limit, String sort,String query, String columns, String navigates, String parentFilter,HttpServletRequest request) {DataFetchResponseInfo response = moduleService.fetchDataInner(moduleName, start, limit, sort,query, columns, navigates, parentFilter, (SqlModuleFilter) null, request);Map<String, Object> result = new HashMap<String, Object>();result.put("records", response.getMatchingObjects());result.put("totalCount", response.getTotalRows());return result;}/** * 新增記錄的時候,在後台取得預設值 *  * @param moduleName * @param parentFilter * @param navigates * @param request * @return */@RequestMapping(value = "/getnewdefault.do", method = RequestMethod.POST)public @ResponseBodyObject getRecordNewDefault(String moduleName, String parentFilter, String navigates,HttpServletRequest request) {return moduleService.getRecordNewDefault(moduleName, parentFilter, navigates, request);}@RequestMapping(value = "/fetchdata.do/{id}", method = RequestMethod.GET)public @ResponseBodyObject getRecordById(String moduleName, @PathVariable("id") String id, HttpServletRequest request) {log.debug("根據主鍵取得模組的一條記錄:" + moduleName + "," + id);Map<String, Object> result = new HashMap<String, Object>();result.put("totalCount", 1);List<Object> records = new ArrayList<Object>();try {records.add(moduleDAO.getModuleRecord(moduleName, id, request).toString());} catch (Exception e) {e.printStackTrace();}result.put("records", records);log.debug("getRecordById傳回值:" + result.toString());return result;}/** * 建立一條記錄 *  * @param moduleName * @param inserted * @param request * @return */@RequestMapping(value = "/create.do", method = RequestMethod.POST)public @ResponseBodyDataInsertResponseInfo addWithNoPrimaryKey(String moduleName, @RequestBody String inserted,HttpServletRequest request) {return add(moduleName, inserted, request);}@RequestMapping(value = "/create.do/{id}", method = RequestMethod.POST)public @ResponseBodyDataInsertResponseInfo add(String moduleName, @RequestBody String inserted,HttpServletRequest request) {DataInsertResponseInfo result = null;try {result = moduleService.add(moduleName, inserted, request);if (result.getKey() != null) // 如果是空的話,那麼就沒有儲存,錯誤原因已經在errorMessage裡了result.getRecords().add(moduleDAO.getModuleRecord(moduleName, result.getKey(), request).toString());} catch (DataAccessException e) {e.printStackTrace();if (result == null)result = new DataInsertResponseInfo();result.setResultCode(ModuleService.STATUS_VALIDATION_ERROR);} catch (Exception e) {e.printStackTrace();if (result == null)result = new DataInsertResponseInfo();result.getErrorMessage().put("error", e.getMessage());result.setResultCode(ModuleService.STATUS_FAILURE);}return result;}/** * 修改記錄 *  * @param moduleName * @param id * @param oldid * @param operType * @param updated * @param request * @return */@RequestMapping(value = "/update.do/{id}", method = RequestMethod.PUT)public @ResponseBodyDataUpdateResponseInfo update(String moduleName, @PathVariable("id") String id, String oldid,String operType, @RequestBody String updated, HttpServletRequest request) {DataUpdateResponseInfo result = null;_Module module = ApplicationService.getModuleWithName(moduleName);// 如果主索引值修改了,那麼先進行主鍵的修改if (oldid != null && (!oldid.equals(id))) {try {result = moduleService.changeRecordId(moduleName, id, oldid);} catch (ConstraintViolationException e) {e.printStackTrace();result = new DataUpdateResponseInfo();if (e.getCause().toString().toLowerCase().indexOf("primary key") >= 0)result.getErrorMessage().put(module.getTf_primaryKey(), "修改過後的主鍵與原有的主索引值重複!");elseresult.getErrorMessage().put(module.getTf_primaryKey(), "當前主鍵與子模組有約束關係,不可以修改!");result.setResultCode(ModuleService.STATUS_VALIDATION_ERROR);}if (!result.getResultCode().equals(0))return result;}// 修改記錄try {result = moduleService.update(moduleName, id, operType, updated, request);result.getRecords().add(moduleDAO.getModuleRecord(moduleName, id, request).toString());} catch (DataAccessException e) {result = new DataUpdateResponseInfo();result.setResultCode(ModuleService.STATUS_VALIDATION_ERROR);} catch (Exception e) {e.printStackTrace();result = new DataUpdateResponseInfo();result.getErrorMessage().put("error", e.getMessage());result.setResultCode(ModuleService.STATUS_FAILURE);}return result;}/** * 刪除記錄 *  * @param moduleName * @param id * @param request * @return */@RequestMapping(value = "/remove.do/{id}", method = RequestMethod.DELETE)public @ResponseBodyDataDeleteResponseInfo remove(String moduleName, @PathVariable String id,HttpServletRequest request) {DataDeleteResponseInfo result = null;try {result = moduleService.remove(moduleName, id, request);} catch (DataAccessException e) {result = new DataDeleteResponseInfo();String errormessage = ModuleServiceFunction.addPK_ConstraintMessage(e, moduleName);result.setResultMessage(-1, errormessage != null ? errormessage: "請檢查與本記錄相關聯的其他資料是否全部清空!<br/>");} catch (Exception e) {result = new DataDeleteResponseInfo();result.setResultMessage(-1, e.getMessage());}return result;}@RequestMapping(value = "/removerecords.do")public @ResponseBodyDataDeleteResponseInfo removeRecords(String moduleName, String ids, String titles,HttpServletRequest request) {DataDeleteResponseInfo result = null;String[] idarray = ids.split(",");String[] titlearray = titles.split("~~");result = new DataDeleteResponseInfo();for (int i = 0; i < idarray.length; i++) {try {DataDeleteResponseInfo recordDeleteResult = moduleService.remove(moduleName, idarray[i],request);if (recordDeleteResult.getResultCode() == 0)result.getOkMessageList().add(titlearray[i]);else {if (recordDeleteResult.getErrorMessageList().size() > 0)result.getErrorMessageList().add("【" + titlearray[i] + "】" + recordDeleteResult.getErrorMessageList().get(0));elseresult.getErrorMessageList().add("【" + titlearray[i] + "】" + "未知錯誤!");}} catch (DataAccessException e) {String errormessage = ModuleServiceFunction.addPK_ConstraintMessage(e, moduleName);result.getErrorMessageList().add("【" + titlearray[i] + "】" + (errormessage != null ? errormessage : "關聯的資料未清空!"));} catch (Exception e) {result.getErrorMessageList().add("【" + titlearray[i] + "】" + e.getMessage());}}result.setResultCode(result.getErrorMessageList().size());return result;}}

        5、在service包中加入ModuleService.java,用來完成查詢,新增,刪除,修改的功能。        6、加入ModuleDAO.java ,用來根據模組名稱,起始行,終止行,篩選條件等來從資料庫中取得資料。這些類太多了,就不一一寫明了。




高一英語外研版必修3 5模組應用作文模板的寫作課教學設計

第一段(引言段)S(1)引出主題(topic),即本文要討論的問題。 S(2萬能英語作文模板(I)說明原因型模組(一) Nowadays ,there are more and
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.