Learn Extjs5 with me. (37--design of individual modules [5 get Module List data])
Wrote for a few months, finally a little look forward, finally to get data from the backstage. The background of spring MVC and service can only be simple to say, the inside added dozens of classes, interested in downloading the source of their own look. Here is a general list of modules to take the data flow, this process is applicable to all modules. I this background processing program is also the unified processing of all the modules, including data lookup, add, modify, delete are the same.
Drawing is not a strong point, you can understand it. 1, the grid after rendering good will be through the Stroe to obtain data; 2, Stroe will send AJAX requests to the background server, Spring MVC will find the Modulecontroller in accordance with the request to obtain the corresponding function of the data, 3, the controller calls M The function in the oduleservice obtains the data; 4, the service calls the Moduledao function to get the data from the database, and then returns the first level to the store, which is then displayed in the grid.
Now we do the extjs5 side of the change, the original store used local data, now to change the remote call data,
1, first modify the model's generating function modelfactory.js. This function generates the model based on the definition of the incoming module, which is mainly generated by the Fields property and proxy. There are also functions to be used later, such as determining whether the record can be modified, deleted, and so on. There is also a function that obtains the flag field for this record.
/** * Generates the module's model */ext.define (' App.view.module.factory.ModelFactory ', {statics: {getmodelbymodule) according to the modules ' data: 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_moduleNa ME},API: {//Add rest/here because in Web. XML//<url-pattern>/rest/*</url-pattern> This sentence, spring will be based on rest// The following parameters go to match 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,writeallfiel ds:false//fields that have not been modified are not added to the JSON for update and delete},listeners: {exceptioN:function (proxy, response, operation) {//Add error message to proxy, display error message in sync to store, delete this property after display Proxy.errorinfo = Ext.decode (Response.responsetext, true); If an error message parsing error occurs, add a default if (!proxy.errorinfo) Proxy.errorinfo = {resultcode:-1, ErrorMessage: ' Unknown Reason: ' + 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 ())},//whether this record can be modified 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;},//Whether this record can be manipulated canoperate:function () {if (this.module.tf_hasAuditing && thi S.get (' tf_auditinged ')) return False;return true;},//Whether this record can delete candelete:function () {if (this.module.tf_hasAuditing && this.get (' tf_auditinged ')) return {CANDELETE:FALse,message: ' "' + this.gettitletpl () + '" has been audited and is not allowed to delete! '}; if (This.module.tf_hasApprove && this.get (' tf_shnowcount ') > 0) return {candelete:false,message: ' "' + THIS.G ETTITLETPL () + ' "is being approved or has been approved for completion, do not allow deletion! '}; Return true;},//gets the primary key value Getidvalue:function () {return this.get (this.idproperty);},//Gets the name field of the current record 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];v Ar field = {name:fd.tf_fieldname,title:fd.tf_title,type:this.gettypebystr (fd.tf_fieldtype)};if (Field.type = = ' Strin G ') {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 '; Boolean ': Return ' boolean ', Case ' Integer ': return ' int ', case ' date ': Return ' date ', Case ' Datetime ': return ' date '; Uble ': Case ' float ': ' Percent ': return ' float ';d efault:return ' string ';}},//if it is an empty string, return nullconverttonull:function (v) {return v V:null;}});
2. Generate the file Gridstore.js in the App.store directory. This is the definition of the class of the 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 can be unlimited pull down, but delete and add, reload have a problem, temporarily do not use config: { Extraparams: {},navigates: []//Navigation properties selected Case},constructor:function (param) {var me = This;this.pagesize = 20;this.extrapar AMS = {};this.navigates = [];//has a navigation constraint added when creating if (Param.modulePanel.param) {var DNV = Param.modulepanel.param.defaultnavigatevalues;this.setdefaultnavigates (DNV);} This.callparent (arguments);},listeners: {//When calling proxy for Ajax, add parameters to Store.proxy, after the call is complete, remove all the extraparams parameters//So model.proxy can be more store, do not interfere with each other beforeprefetch:function (store) {for (Var i In store.extraparams) store.proxy.extraparams[i] = store.extraparams[i];},//buffered = True, Prefetchprefetch is performed: function (store, records, successful) {for (var i in store.extraparams) Delete store.proxy.extraparams[i];},//buffered = f Alse, executed by 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, modify the App.view.module.Module class, the store and model generation methods are changed.
Initcomponent:function () {console.log (This.modulename + ' is being created ');//Get the definition data of the current module from Mainmodel, including the fields and information about the various settings var Mainmodel = This.up (' App-main '). Getviewmodel (); this.module = Mainmodel.getmoduledefine (this.modulename); var viewmodel = new Ext.create (' App.view.module.ModuleModel ', {//) pass the module's definition information to the module's ViewModelmodule:this.module}); This.setviewmodel ( ViewModel); this.glyph = This.getviewmodel (). Get (' tf_glyph '); Because the bind of the glyph above is invalid, it is necessary to add the glyph setting here 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 ',//Navigation area region: ' West ',
4, the background server side in the Com.jfok.server.controller to join the Modulecontroller.java, which is the spring MVC control class.
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 for all modules is done in the controller that calls this class's function to complete the * * @author Jiangfeng * */PUBL IC class Modulecontroller {@Resourceprivate Systembasedao Systembasedao; @Resourceprivate moduleservice ModuleService; @Resourceprivate Moduledao moduledao;private static final log log = Logfactory.getlog (modulecontroller.class);/** * Data obtained from the foreground/@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 nav Igates, 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;} /** * When adding records, the default values are obtained in the background * * @param modulename * @param parentfilter * @param navigates * @param request * @return */@Reque Stmapping (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 ("gets a record of the module based on the primary key:" + 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 return value:" + result.tostring ()); return result; /** * Create a record * * @param modulename * @param inserted * @param request * @return */@RequestMapping (value = "/create.do", M Ethod = 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)//if it is empty, then there is no save, the cause of the error is already in 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;} /** * Modify Record * * @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, HttpS Ervletrequest request) {dataupdateresponseinfo result = Null;_module Module = Applicationservice.getmodulewithname ( ModulENAME);//If the primary key value is modified, then the primary key is modified 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 (), " The modified primary key is duplicated with the original primary key value! Elseresult.geterrormessage (). Put (Module.gettf_primarykey (), "The current primary key has a constraint relationship with the submodule and cannot be modified!" "); Result.setresultcode (moduleservice.status_validation_error);} if (!result.getresultcode (). Equals (0)) return result; Modify record 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;} /** * Delete Record * * @param modulename * @param ID * @param request * @return */@RequestMapping (value = "/remove.do/{id}", Meth OD = 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: "Please check that all other data associated with this record is emptied!" <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); 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] +" "" + " Unknown error! ");}} catch (DataAccessException e) {String errormessage = Moduleservicefunction.addpk_constraintmessage (E, moduleName); Result.geterrormessagelist (). Add ("" "+ Titlearray[i] +" "" + (errormessage! = null? errormessage: "The associated data is not emptied! "));} catch (Exception e) {result.geterrormessagelist (). Add ("" "+ Titlearray[i] +" "" + E.getmessage ());}} Result.setresUltcode (Result.geterrormessagelist (). Size ()); return result;}}
5, in the service package to add Moduleservice.java, to complete the query, add, delete, modify the function. 6. Add Moduledao.java to obtain data from the database according to the module name, start line, termination line, filter condition, etc. There are too many of these classes to be written down.
Learn Extjs5 with me. (37--design of individual modules [5 get Module List data])