DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Infrastructure as Code (IaC) Beyond the Basics
  • The Full-Stack Developer's Blind Spot: Why Data Cleansing Shouldn't Be an Afterthought
  • Metrics at a Glance for Production Clusters
  • Data Quality: A Novel Perspective for 2025
  1. DZone
  2. Coding
  3. Frameworks
  4. Ext JS 4 Spring MVC CRUD example

Ext JS 4 Spring MVC CRUD example

By 
Tousif  Khan user avatar
Tousif Khan
·
Jul. 15, 14 · Interview
Likes (2)
Comment
Save
Tweet
Share
51.5K Views

Join the DZone community and get the full member experience.

Join For Free

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<book> 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<book> books = new arraylist<book>();

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<book> 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<string, list<book>> loadallbooks()
{
map<string, list<book>> books = new hashmap<string, list<book>>();
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('<div id="{0}"></div>', 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.


Spring Framework Ext JS

Published at DZone with permission of Tousif Khan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!