Ext JS 4 Spring MVC CRUD example
in my last post on extjs 4 mvc, i have demonstrated the use of extjs 4 mvc to create a simple create-read-update-delete application using extjs only. today we will go to see how to use that extjs part for ui and use spring mvc to manage the books records on server side using spring. let first start by creating spring’s webmvc configurer class. i am using spring’s new xml-free approach and if you are new to it, i recommend you to please go through my previous post. package org.techzoo.springmvc.bootstrap; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configuration; import org.springframework.web.servlet.config.annotation.enablewebmvc; import org.springframework.web.servlet.config.annotation.resourcehandlerregistry; import org.springframework.web.servlet.config.annotation.viewcontrollerregistry; import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; import org.springframework.web.servlet.view.internalresourceviewresolver; @configuration @enablewebmvc @componentscan(basepackages = {"org.techzoo.springmvc"}) public class mywebmvcconfigurer extends webmvcconfigureradapter { @override public void addresourcehandlers(resourcehandlerregistry registry) { registry.addresourcehandler("/resources/**") .addresourcelocations("/resources/"); } @override public void addviewcontrollers(viewcontrollerregistry registry) { registry.addviewcontroller("/") .setviewname("index"); } @bean public internalresourceviewresolver viewresolver() { internalresourceviewresolver resolver = new internalresourceviewresolver(); resolver.setprefix("/web-inf/views/"); resolver.setsuffix(".jsp"); return resolver; } } create a book bean now, this bean is work as a value object and represent a single record in grid. package org.techzoo.springmvc.vo; /** * author: tousif khan */ public class book { private int id; private string title; private string author; private int price; private int qty; public book() {} public book(int id, string title, string author, int price, int qty) { super(); this.id = id; this.title = title; this.author = author; this.price = price; this.setqty(qty); } //getter-setters goes here... @override public string tostring() { return string.format("book [title = %s, author = %s]", title, author); } } now create a bookdao interface and implement it. package org.techzoo.springmvc.dao; import java.util.list; import org.springframework.stereotype.component; import org.techzoo.springmvc.vo.book; @component public interface bookdao { public boolean addbook(book book); public void updatebook(book book); public list listbooks(); public book getbookbyid(integer bookid); public boolean removebook(book book); } to make it more simple, i am using book list but you can extend it to save it relational table. see my springmvc-hibernate grud tutorial for more details. package org.techzoo.springmvc.dao; import java.util.arraylist; import java.util.list; import org.springframework.stereotype.repository; import org.techzoo.springmvc.vo.book; @repository public class bookdaoimpl implements bookdao { private static list books = new arraylist(); static { books.add(new book(1001, "jdbc, servlet and jsp", "santosh kumar", 300, 12000)); books.add(new book(1002, "head first java", "kathy sierra", 550, 2500)); books.add(new book(1003, "java scjp certification", "khalid mughal", 650, 5500)); books.add(new book(1004, "spring and hinernate", "santosh kumar", 350, 2500)); books.add(new book(1005, "mastering c++", "k. r. venugopal", 400, 1200)); } @override public boolean addbook(book book) { return books.add(book); } @override public boolean removebook(book book) { return books.remove(book); } @override public list listbooks() { return books; } @override public void updatebook(book book) { int index = books.indexof(book); if(index != -1) { books.add(index, book); } } @override public book getbookbyid(integer bookid) { book b = null; for(book b1 : books) { if(b1.getid() == bookid) { return b1; } } return b; } } now it’s time to create a book controller. package org.techzoo.springmvc.controller; import java.util.hashmap; import java.util.list; import java.util.map; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.validation.objecterror; import org.springframework.web.bind.methodargumentnotvalidexception; import org.springframework.web.bind.annotation.exceptionhandler; 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 org.techzoo.springmvc.dao.bookdao; import org.techzoo.springmvc.vo.book; @controller @requestmapping("api") public class bookcontroller { bookdao bookbao; @autowired public bookcontroller(bookdao bookbao) { this.bookbao = bookbao; } @requestmapping(value = "/index") public string index() { return "index"; } @requestmapping (value = "book/save", method = requestmethod.post) @responsebody public boolean savebook(@requestbody book book) { return bookbao.addbook(book); } @responsebody @requestmapping (value = "book/loadbooks") public map> loadallbooks() { map> books = new hashmap>(); books.put("books", bookbao.listbooks()); return books; } @requestmapping (value = "book/delete", method = requestmethod.post) @responsebody public boolean deletebooks(@requestbody book book) { return bookbao.removebook(book); } @requestmapping (value = "book/updatebook", method = requestmethod.post) @responsebody public boolean updatebooks(@requestbody book book) { bookbao.updatebook(book); return true; } } extjs code looks similar to previous example with a little change. i have changes the local store to server ajax proxy and after each delete/add/update operation, we will load the all record from server to make grid update. ext.onready(function () { ext.define('techzoo.model.book', { extend: 'ext.data.model', fields: [ {name: 'id', type: 'int'}, {name: 'title', type: 'string'}, {name: 'author', type: 'string'}, {name: 'price', type: 'int'}, {name: 'qty', type: 'int'} ] }); ext.define('techzoo.store.books', { extend : 'ext.data.store', storeid: 'bookstore', model : 'techzoo.model.book', fields : ['id', 'title', 'author','price', 'qty'], proxy: { type: 'ajax', url: '/springmvc-extjs-crud/api/book/loadbooks', reader: { type: 'json', root: 'books' } }, autoload: true }); ext.define('techzoo.view.bookslist', { extend: 'ext.grid.panel', alias: 'widget.bookslist', title: 'books list - (extjs springmvc example - @ tousif khan)', store: 'books', initcomponent: function () { this.tbar = [{ text : 'add book', action : 'add', iconcls : 'book-add' }]; this.columns = [ { header: 'title', dataindex: 'title', flex: 1 }, { header: 'author', dataindex: 'author' }, { header: 'price', dataindex: 'price' , width: 60 }, { header: 'quantity', dataindex: 'qty', width: 80 }, { header: 'action', width: 50, renderer: function (v, m, r) { var id = ext.id(); ext.defer(function () { ext.widget('image', { renderto: id, name: 'delete', src : 'resources/images/book_delete.png', listeners : { afterrender: function (me) { me.getel().on('click', function() { var grid = ext.componentquery.query('bookslist')[0]; if (grid) { var sm = grid.getselectionmodel(); var rs = sm.getselection(); if (!rs.length) { ext.msg.alert('info', 'no book selected'); return; } ext.msg.confirm('remove book', 'are you sure you want to delete?', function (button) { if (button == 'yes') { //grid.store.remove(rs[0]); var book = rs[0].getdata(); ext.ajax.request({ url: '/springmvc-extjs-crud/api/book/delete', method : 'post', jsondata: book, success: function(response){ var grid = ext.componentquery.query('bookslist')[0]; grid.getstore().load(); } }); } }); } }); } } }); }, 50); return ext.string.format('', id); } } ]; this.callparent(arguments); } }); ext.define('techzoo.view.booksform', { extend : 'ext.window.window', alias : 'widget.booksform', title : 'add book', width : 350, layout : 'fit', resizable: false, closeaction: 'hide', modal : true, config : { recordindex : 0, action : '' }, items : [{ xtype : 'form', layout: 'anchor', bodystyle: { background: 'none', padding: '10px', border: '0' }, defaults: { xtype : 'textfield', anchor: '100%' }, items : [{ name : 'title', fieldlabel: 'book title' },{ name: 'author', fieldlabel: 'author name' },{ name: 'price', fieldlabel: 'price' },{ name: 'qty', fieldlabel: 'quantity' }] }], buttons: [{ text: 'ok', action: 'add' },{ text : 'reset', handler : function () { this.up('window').down('form').getform().reset(); } },{ text : 'cancel', handler: function () { this.up('window').close(); } }] }); ext.define('techzoo.controller.books', { extend : 'ext.app.controller', stores : ['books'], views : ['bookslist', 'booksform'], refs : [{ ref : 'formwindow', xtype : 'booksform', selector: 'booksform', autocreate: true }], init: function () { this.control({ 'bookslist > toolbar > button[action=add]': { click: this.showaddform }, 'bookslist': { itemdblclick: this.onrowdblclick }, 'booksform button[action=add]': { click: this.doaddbook } }); }, onrowdblclick: function(me, record, item, index) { var win = this.getformwindow(); win.settitle('edit book'); win.setaction('edit'); win.setrecordindex(index); win.down('form').getform().setvalues(record.getdata()); win.show(); }, showaddform: function () { var win = this.getformwindow(); win.settitle('add book'); win.setaction('add'); win.down('form').getform().reset(); win.show(); }, doaddbook: function () { var win = this.getformwindow(); var store = this.getbooksstore(); var values = win.down('form').getvalues(); var action = win.getaction(); // var book = ext.create('techzoo.model.book', values); var url = ''; if(action == 'edit') { url = '/springmvc-extjs-crud/api/book/updatebook'; } else { url = '/springmvc-extjs-crud/api/book/save'; } ext.ajax.request({ url: url, method : 'post', jsondata: values, success: function(response){ store.load(); } }); win.close(); } }); ext.application({ name : 'techzoo', controllers: ['books'], launch: function () { ext.widget('bookslist', { width : 500, height: 300, renderto: 'output' }); } } ); }); output: open the html file in any browser, the output will look similar to below. you can click to add new book record in grid.
July 15, 2014
by Tousif Khan
·
50,845 Views
·
2 Likes