Learn Extjs5 with me. (37--design of individual modules [5 get Module List data])

Source: Internet
Author: User
Tags log log

Learn Extjs5 with me. (37--design of individual modules [5 get Module List data])
Wrote for a few months, finally a little look forward, eventually to get data from the backstage. Spring MVC and service in the background can simply be said, adding dozens of classes. Interested in downloading the source code to see for yourself. 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 entire module of the unified processing, including data lookup, add, change, delete are the same.

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvamzvaw==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70 /gravity/center ">

Drawing is not a strength.        You can read it. 1, the grid after rendering good will be through Stroe to obtain data; 2, Stroe will send AJAX requests to the background server,spring MVC will find the corresponding data in the Modulecontroller to obtain the function; 3, the Controller        Call the function in ModuleService to get the data. 4. The service then calls the Moduledao function to get the data from the database, and then returns the first level to the store. displayed in the grid again.

Now let's do the EXTJS5-side changes first. The original store uses local data, which is now changed to remotely called data,
1, first change the model of the 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. Other functions to be used in the future. For example, infer whether this record can be changed, deleted, etc. functions.

The other is the function that gets 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: {//Here Add rest/is due to in Web. XML//<url-pattern>/rest/*</url-pattern> this sentence. Spring will match according to the number of rest//after 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: ' DELE TE '},reader: {type: ' json ', Root: ' Records ', Totalproperty: ' TotalCount '},writer: {type: ' json ', writerecordid:true,w riteallfields:false//fields that have not been modified are not added to the JSON for update and delete},listeners: {exceptioN:function (proxy, response, operation) {//Add the error message to the proxy, and the error message is displayed in sync to store. Delete this property after display Proxy.errorinfo = Ext.decode (Response.responsetext, true);//Assuming an error message parsing error, 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 ())},//If this record can be changed 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 is sufficient for Operation Canoperate:function () {if (this.module.tf_hasAuditing && this . 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, does not agree to delete operation!" if (This.module.tf_hasApprove && this.get (' tf_shnowcount ') > 0) return {candelete:false,message: ' "' + THIS.G ETTITLETPL () + ' "is being approved or has been approved, do not agree to delete operation! '}; 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 ': Case ' Percent ': return ' float ';d efault:return ' string ';}},//assumes an empty string, returns nullconverttonull:function (v) {return v?


2. Generate file Gridstore.js in App.store folder. 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 pull down indefinitely. However, delete and add, reload have a problem, temporary without config: {extraparams: {},navigates: []//Navigation properties selected},constructor:function (param) {var me = this ; this.pagesize = 20;this.extraparams = {};this.navigates = [];//has a navigation constraint added when created if (Param.modulePanel.param) {var DNV = param . Modulepanel.param.defaultnavigatevalues;this.setdefaultnavigates (DNV);} This.callparent (arguments);},listeners: {//When calling proxy for Ajax. Add the number of parameters to the Store.proxy after the call is complete. Delete all extraparams parameters//So that 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, running Prefetchprefetch:function (store, Records,  Successful) {for (var i in store.extraparams) Delete store.proxy.extraparams[i];},//buffered = False, Loadbeforeload is running : 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, change the App.view.module.Module class. Change the way the store and model are generated.

Initcomponent:function () {console.log (This.modulename + ' is being created ');//Get the definition data of the current module from Mainmodel. Contains information about fields and 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 viewmodelmodule of this module: This.module}); This.setviewmodel (viewmodel); this.glyph = This.getviewmodel (). Get (' tf_glyph '); Because the glyph bind above is invalid, it is necessary to add glyph settings 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, backend server side add Modulecontroller.java under Com.jfok.server.controller, this is the control class of 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 for all modules is the function that calls this class to complete the controller inside * * @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 ("Get a record of the module by 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;}  /** * Change 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);//Assuming that the primary key value is changed, first change the primary key 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 (), " After the change of the primary key and the original primary key value repeatedly!

"); Elseresult.geterrormessage (). Put (Module.gettf_primarykey ()," The current primary key has a constraint relationship with the child module. Cannot be changed! "); Result.setresultcode (moduleservice.status_validation_error);} if (!result.getresultcode (). Equals (0)) return result; Change 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) {Datadeleteresponseinforesult = Null;try {result = Moduleservice.remove (modulename, ID, request),} catch (DataAccessException e) {result = new Da Tadeleteresponseinfo (); String errormessage = Moduleservicefunction.addpk_constraintmessage (E, modulename); Result.setresultmessage (-1, ErrorMessage! = null? ErrorMessage: "Please check if 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, add Moduleservice.java in service package, used to complete query, add, delete. The function of the change.

6, add Moduledao.java, used to base on the module name. Starting lines, terminating rows, filtering criteria, and so on to get data from the database. 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])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.