March 21, 2008

CRUD application using ExtJS and Java

Finally I have the CRUD application built on ExtJS and Java. CRUD stands for Create Read Update and Delete. This application will show how to build a simple but complete web application. I have used Java as my server side and Oracle XE to store my data. You can use any server side technology and persistence technology. Now let’s look at the application.



The major reason to build this web application was to make use of multiple Ext components and show how they can be used in an application. Please note that I have kept the code simple. You will find many improvements that can be made. I leave it as an exercise for you to do. The Application has three parts: Front End (Ext), server side (Java Servlets) and back end (Oracle).

The Front End:
The front end consists of a HTML page and JavaScript file. The complete application code goes into this JavaScript file. We have a main menu, forms for creating, editing and a grid view to display all the records available. The main menu is stick to the body as toolbar. I have implemented both drop down menu and normal action button to demonstrate how both of these can be implemented.

Below is a snap shot of the front-end:



The Server Side:
I work on java and love it! So my server side is Java. You may use PHP,.Net or any other of your choice. I have four Servlets create; each for my major operations. With minor tweaking, you can easily reduce the number (yet another exercise!). All these Servlets connect to Oracle XE for INSERT, SELECT, UPDATE or DELETE operations.

The Back End:
Finally the last part of the application: the back end where all the data is stored. Oracle provides its version of DB freely named Express Edition. The DB has all features available for its commercial version. But XE has some restriction like your DB size cannot exceed 2GB. But the product comes with a very good web application to do all sort of operations from admin to application building.

Our table consists of four fields: Name, Age, City and Phone number. I have not specified any primary key but for update operation I make use of name as search field. Below is the table structure:


The Code:
Enough of background! Let’s have a look at the Ext coding:
app = function() {

var createForm;
var updateForm;
var ds;
var dataGrid;
var menu;
var updateMenuItem;
var createMenuItem;
var readMenuItem;
var deleteMenuItem;
var tb;
var sm;

var onCreateClick = function() {
createForm.show();
}

var onReadClick = function() {  
dataGrid.show();
ds.load({params:{start:0,limit:3,forumId: 4}});

}  

var onUpdateClick = function() {
if(sm.getSelected()) {
var record = sm.getSelected();

var rname = record.get('name');    
var nameComponent = updateForm.getComponent('upName');

var rage = record.get('age');    
var ageComponent = updateForm.getComponent('upAge');

var rcity = record.get('city');    
var cityComponent = updateForm.getComponent('upCity');

var rphone = record.get('phone');    
var phoneComponent = updateForm.getComponent('upPhone');

nameComponent.setValue(rname);  
ageComponent.setValue(rage);
cityComponent.setValue(rcity);
phoneComponent.setValue(rphone);

updateForm.show();
} else {
Ext.MessageBox.alert("Error!!!","Please select a record that you would like to update!
For selecting a record, click on Read and choose any record from the data grid.");
}
}


var onDeleteClick = function() {
if(sm.getSelected()) {
var record = sm.getSelected();    
var rname = record.get('name');
Ext.Ajax.request({url:'DeleteAction',success: doneFunction,failure: errorFunction,params:{name:rname}});
} else {
Ext.MessageBox.alert("Error!!!","Please select a record that you would like to delete!
For selecting a record, click on Read and choose any record from the data grid.");
}
}

var saveButtonHandler = function() {   
createForm.form.submit({url:'FormAction', waitMsg:'Saving Data...',success:doneFunction});
}

var updateButtonHandler = function() {   
updateForm.form.submit({url:'UpdateAction', waitMsg:'Updating Data...',success:doneFunction});
}

var closeButtonHandler = function() {
createForm.hide();
}

var cancelButtonHandler = function() {
updateForm.hide();
}

var doneFunction = function(form,action) {   
Ext.MessageBox.alert("Save Status","Data Saved to DB");
ds.load(); 
}

var errorFunction = function() {
Ext.MessageBox.alert("Error","Error Error Error ");

}

var onRowClick = function(SelectionModel,rowIndex,record)  {

}

return {

init:function() {

menu = new Ext.menu.Menu();
createMenuItem = new Ext.menu.Item({text:'Create',handler:onCreateClick});
readMenuItem = new Ext.menu.Item({text:'Read',handler:onReadClick});
updateMenuItem = new Ext.menu.Item({text:'Update',handler:onUpdateClick});
deleteMenuItem = new Ext.menu.Item({text:'Delete',handler:onDeleteClick});


menu.add(createMenuItem,readMenuItem,updateMenuItem,deleteMenuItem);   

tb = new Ext.Toolbar();
tb.render('menu'); 
tb.add({text:'Operations',menu: menu});
tb.add({text:'Create',handler: onCreateClick});
tb.add({text:'Read',handler:onReadClick});
tb.add({text:'Update',handler:onUpdateClick});
tb.add({text:'Delete',handler:onDeleteClick});


createForm = new Ext.FormPanel({applyTo:'createForm',
bodyStyle:'padding:10px',
title:'Create data record',
labelWidth:50,
items:[new Ext.form.TextField({fieldLabel:'Name',
name:'name'}),
new Ext.form.NumberField({fieldLabel:'Age',
name:'age',  
width:25,
maxLength :2}),
new Ext.form.TextField({fieldLabel:'City',
name:'city'}),
new Ext.form.NumberField({fieldLabel:'Phone',
name:'phone'})            
],
buttons:[{text:'Save',handler:saveButtonHandler},
{text:'Close',handler:closeButtonHandler} 
]
});

ds = new Ext.data.Store({
url:'ReadToList',
reader: new Ext.data.XmlReader({record:'record'},
['name','age','city','phone'])
});

var cm = new Ext.grid.ColumnModel([{header: "Name", width:80, dataIndex: 'name',sortable: true},
{header: "Age", width: 50, dataIndex: 'age',sortable: true},
{header: "City", width: 100, dataIndex: 'city',sortable: true},
{header: "Phone", width: 100, dataIndex: 'phone',sortable: true}
]); 

sm = new Ext.grid.RowSelectionModel({singleSelect:'true'});
sm.addListener('rowselect',onRowClick,this);

var tbp = new Ext.PagingToolbar({pageSize:3,store:ds,displayInfo:true});


dataGrid = new Ext.grid.GridPanel({applyTo:'readPanel',
ds:ds,
cm:cm,
sm:sm,
tbar:tbp,
title:'CRUD Data from Database'    
});

updateForm = new Ext.FormPanel({applyTo:'updateForm',
bodyStyle:'padding:10px',
title:'Update data record',
labelWidth:50,
items:[new Ext.form.TextField({id:'upName',
fieldLabel:'Name',                    
name:'uname'}),
new Ext.form.NumberField({id:'upAge',
fieldLabel:'Age',
name:'uage',  
width:25,
maxLength :2}),
new Ext.form.TextField({id:'upCity',
fieldLabel:'City',
name:'ucity'}),
new Ext.form.NumberField({id:'upPhone',
fieldLabel:'Phone',
name:'uphone'})            
],
buttons:[{text:'Update',handler:updateButtonHandler},
{text:'Cancel',handler:cancelButtonHandler} 
]
});
} 
};
}();
Some Important points to remember for beginners :
  • Form always returns JSON. Code your JSON carefully on the server side.
  • When you return XML as your response, set the appropriate MIME.

Last Words:
You can download deployable war file or the complete Eclipse project and modify it. I also have the DDL to create the database table. Some of the improvements you can try are:
  • Validation to form inputs
  • Pagination for the Grid display
  • Display various forms using card layout or tabbed layout

Till next post: Keep Progarmming! :)

Read other articles on ExtJS!

16 comments :

OOO said...

Hey Abdel,
I came across your BLOG after searching for an article on "How to upload multiple files using Struts". The articles that you write related to new technologies are really good. I also read your latest post related to EXT and found out about the free Express Edition DB from Oracle. I am also a Java/J2EE developer and have been looking for some free DBs for quite a while. I have used MySql in the past, but its good to have free edition of Oracle db. keep up the good work dude.

Ricardo Lima said...

Hey Abdel,

Very nice post. I really enjoy your blog, but I have a doubt about your program. Why is the "onRowClick" handler function empty? Keep up the good work!

Olakara said...

Ricardo,
Thanks for the visit. "onRowClick" is simply blank because I doing some R&D. But I didn't want lots of functionality into the application and wanted it simple.
-- Abdel

Anonymous said...

Nice blog post. I just started giving EXT a try, and so far I've been impressed with what I can do with it. I've studied the examples on their website a lot, and it's refreshing to see a different example. As far as the server side logic is concerned, I'm working with an open source project called Skyway Builder (www.skywayperspectives.org). It lets me easily implement the server-side logic using models (instead of writing code) that are deployed using the Spring framework. I'm going to try to re-implement your server-side logic. I'll keep you posted.

Anonymous said...

It worked. I replaced your db schema with a pojo called Person, and I replaced your servlets with four models (DeleteAction, FormAction, ReadToList, and UpdateAction). I'll try to blog about it tomorrow. Stay tuned.

Olakara said...

Niel,

Great work! I was going through Skyway's site. Its quite impressive. I will try it during my free time. Thanks for the info :)

-- Abdel

Anonymous said...

You can find an explanation of my re-implementation of your application using open source Skyway Builder on my blog. I think you'll like the title of my post (CRUD application using Ext and Java and Skyway). Since I derived my project from your project, I figured I'd derive my title from your title. :-)

Thanks again for your post. I had fun playing with your example project. Let me know when you build another Ext and Java example.

Anonymous said...

Hey Abdel - I haven't forgotten about you. I'll post the project to my blog this weekend. I've been tied up with work. Cheers!

Sébastien Bervoets said...

Hi abdel. I tested your code with a PHP program and all works fine. I just get a problem with the height of the different panels. All are smaller than expected. I use ExtJS 2.1. Is there a solution to fit the height to the content automaticaly ?

Olakara said...

Hi Sébastien,

I am not sure what caused the height issue. And I don't code in PHP :(. May be you can mail me your code and I can have it checked with my friends. Also try posting your code on ExtJS forum. Some PHP experts can help you out.

Regards,
Abdel

Anonymous said...

I came across your blog while trying to lookup for exising java based CRUD application. This is really cool.

I have developed a code free (or minimal, if you need advance customization) self contained CRUD framework. You can find more information at www.datafacade.com

Olakara said...

Hi Buddika,
Thanks for introducing Data Facade. The application I created was for giving demo on Ext framework and Java.

Anonymous said...

Hi,
Nicely Explain
Do the comboBox also return JSON?
If no, do you have any idea, how to pass value of comboBox(extJS) to Java file?

Olakara said...

@sapandiwaker Why do you need combobox to return Json? You can always submit the combobox value to server side using Ajax.

elga silaban said...

thanks for the tutorial.
can i have your email please?

elga silaban said...

thanks for the tutorial.
but i don't have any idea, how to code the json.
can u help through this?