Big Data/Analytics Zone is brought to you in partnership with:

Drabo has posted 12 posts at DZone. View Full User Profile

Mixing ExtJs, JSON-P and Java Web on NetBeans

08.11.2013
| 12784 views |
  • submit to reddit

In a previous article  I demonstrated how to build a ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side.

I- Database schema table

Below the DDL script of the Patient table: 

CREATE TABLE Patient(
Id INT NOT NULL AUTO_INCREMENT,
FirstName VARCHAR(100) NOT NULL,
LastName  VARCHAR(100) NOT NULL, 
Address   VARCHAR(100) NOT NULL,
City      VARCHAR(100) NOT NULL,
Country   VARCHAR(100) NOT NULL,
PRIMARY KEY (ID)
);

II - Client-side : ExtJs  + MVC architecture

We need first to create a new Java Web project ( please, follow this tutorial ) with Spring Web MVC into NetBeans IDE.  Mine was named PatientManagement .

In the second time we create the client side using ExtJs framework and respecting MVC architecture ( Controller and View). Below the picture summarizing the project : 

The index.html file code source  :

<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
    <head>
        <title>PATIENT MANAGEMENT</title>
        <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">
        <script type="text/javascript" src="ext/ext-all.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </head>
    <body></body>
</html>
The app.js  file content :
Ext.Loader.setConfig({
    enabled: true
});

Ext.application({
    name: 'PM',
    appFolder: 'front/app',
    controllers: ['PatientController'],
    autoCreateViewport: true,
    launch: function() {

    }
});

Views :

The AppToolbar.js file content :

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

Ext.define('PM.view.patient.AppToolbar', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.apptoolbar',    
    initComponent: function() {
        this.dockedItems = [
            {xtype: 'toolbar',
                dock: 'top',
                items: [
                    {
                        xtype: 'cycle',
                        showText: 'true',
                        text: '<html><b>Patient</b></html>',
                        width: '300',
                        menu: {
                            xtype: 'menu',
                            width: '150',
                            items: [
                                {
                                    xtype: 'menucheckitem',
                                    text: 'New patient',
                                    action: 'create'
                                },
                                {
                                    xtype: 'menucheckitem',
                                    text: 'Patients list',
                                    action: 'listing'
                                }

                            ]
                        }
                    }
                ]
            }

        ];

        this.callParent(arguments);
    }
});

The AddPatient.js file code source :

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


Ext.define('PM.view.patient.AddPatient', {
    extend: 'Ext.window.Window',
    alias: 'widget.addpatient',
    title: 'Create a patient',
    layout: 'fit',
    autoShow: true,
    initComponent: function() {
        this.items = [
            {
                xtype: 'form',
                bodyStyle: {
                    background: 'none',
                    padding: '10px',
                    border: '0'
                },
                items: [
                    {
                        xtype: 'textfield',
                        name: 'firstname',
                        allowBlank: false,
                        fieldLabel: '<html><b>Firts Name</b></html>'
                    },
                    {
                        xtype: 'textfield',
                        name: 'lastname',
                        allowBlank: false,
                        fieldLabel: '<html><b>Last Name</b></html>'
                    },
                    {
                        xtype: 'textfield',
                        name: 'address',
                        fieldLabel: '<html><b>Address</b></html>',
                        allowBlank: false
                    },
                    {
                        xtype: 'textfield',
                        name: 'city',
                        fieldLabel: '<html><b>City</b></html>',
                        allowBlank: false
                    },
                    {
                        xtype: 'textfield',
                        name: 'country',
                        fieldLabel: '<html><b>Country</b></html>',
                        allowBlank: false

                    }
                ]
            }
        ];
        this.buttons = [
            {
                text: 'Save',
                action: 'save'
            },
            {
                text: 'Cancel',
                scope: this,
                handler: this.close
            }
        ];

        this.callParent(arguments);
    }
});
The viewport  Viewport.js file content :
Ext.define('PM.view.Viewport', {
    extend: 'Ext.container.Viewport',
    alias: 'widget.viewport',    
    items: [
        {
            xtype: 'apptoolbar'
        }],
    initComponent: function() {
       this.callParent(arguments);
    }
}); 

Controller :

The content of PatientController.js is below :

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


Ext.define('PM.controller.PatientController', {
    extend: 'Ext.app.Controller',
    views: ['patient.AddPatient', 'patient.AppToolbar'],
    init: function() {
        this.control({
            'addpatient button[action=save]': {
                click: this.doCreatePatient
            },
            'apptoolbar > toolbar > cycle > menu > menucheckitem[action=create]': {
                click: this.onCreatePatient
            }

        });
    },
    onCreatePatient: function() {
        //The panel to create a patient appears on the screen
        var view = Ext.widget('addpatient');
    },
    //Function to create a new patient
    doCreatePatient: function(button) {
        var win = button.up('window'),
                form = win.down('form'),
                values = form.getValues()
        if (form.getForm().isValid()) {
            Ext.Ajax.request({
                url: 'PatientController',
                method: 'POST',
                params: {
                    patientcreateData: Ext.encode(values)
                },
                scope: this,
                stateful: true
            });

            win.close();
        }
    },
});

In this controller we use the singleton Ext.Ajax  to send an HTTP request to a remote server. In our example we will use the method POST to send the data and we will use the server-side servlet  PatientController.java (see below the code source).  The JSON object is patientcreateData.

The web.xml file has been modified according the project to have index.html file as welcome page.

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

III - Server-side implementation

Below the sample of Java files defining the server-side of the application :

The model  Patient.java  code is here:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.model.patientmanagement;

/**
 *
 * @author constantin
 */
public class Patient {

    private int id;
    private String firstname;
    private String lastname;
    private String address;
    private String city;
    private String country;

    public Patient() {
    }

    public Patient(String firstname, String lastname, String address, String city, String country) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.address = address;
        this.city = city;
        this.country = country;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}

The DAO PatientDao.java file content is here :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dao.patientmanagement;

import com.model.patientmanagement.Patient;
import java.util.List;
import javax.sql.DataSource;

/**
 *
 * @author constantin
 */
public interface PatientDao {

    public void setDataSource(DataSource dataSource);

    public void createPatient(String firstname, String lastname, String address, String city, String country);

    public Patient getPatientById(Integer id);

    public void deletePatient(Integer id);

    public List<Patient> listPatients();

    public void updateFirstName(Integer id, String firstname);

}

The PatientTemplate.java source :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.impl.patientmanagement;

import com.dao.patientmanagement.PatientDao;
import com.model.patientmanagement.Patient;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 *
 * @author constantin
 */
public class PatientTemplate implements PatientDao {

    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;

    @Override
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    @Override
    public void createPatient(String firstname, String lastname, String address, String city, String country) {
        try {
            String Sql = "insert into Patient(firstname, lastname, address, city,country) values (?,?,?,?,?)";
            jdbcTemplateObject.update(Sql, firstname, lastname, address, city, country);

        } catch (DataAccessException ex) {
            System.out.println("Error" + ex.getMessage());
        }
    }

    @Override
    public Patient getPatientById(Integer id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void deletePatient(Integer id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Patient> listPatients() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void updateFirstName(Integer id, String firstname) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

The PatientMapper.java file content is:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.impl.patientmanagement;

import com.model.patientmanagement.Patient;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author constantin
 */
public class PatientMapper implements RowMapper<Patient> {

    @Override
    public Patient mapRow(ResultSet rs, int i) throws SQLException {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        Patient patient = new Patient(); 
        patient.setId(rs.getInt("id"));
        patient.setFirstname(rs.getString("firstname"));
        patient.setLastname(rs.getString("lastname"));
        patient.setAddress(rs.getString("address"));
        patient.setCity(rs.getString("city"));
        patient.setCountry(rs.getString("country"));  
        return patient ;  
    }
}

Here the doPost method code source of the servlet PatientController.java :

 @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        //Get the context of the application
        ServletContext servletContext = this.getServletContext();

        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

        String patientcreateData = request.getParameter("patientcreateData");

        //I parse here the json object
        GenericJsonParser jsonPatient = new GenericJsonParser();
        HashMap<String, String> patientMap = jsonPatient.getJsonMap(patientcreateData);

        String firstname = patientMap.get("firstname");
        String lastname = patientMap.get("lastname");
        String address = patientMap.get("address");
        String city = patientMap.get("city");
        String country = patientMap.get("country");

        PatientTemplate patient = (PatientTemplate) wac.getBean("patienttemplate");
        
        patient.createPatient(firstname, lastname, address, city, country);               

    }

The class to parse Json object is implemented as shown below  (GenericJsonParser.java):

This class is very important since there is no method in JSON-P API to bind Java object and JSON object. It parses the Json object a return a map that is better easy to be used in Java code.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.controller.patientmanagement;

import java.io.StringReader;
import java.util.HashMap;
import javax.json.Json;
import javax.json.stream.JsonParser;
import static javax.json.stream.JsonParser.Event.END_OBJECT;
import static javax.json.stream.JsonParser.Event.KEY_NAME;

/**
 *
 * @author constantin Drabo
 * This class allow you to parse a  Json object coming from client side
 */
public class GenericJsonParser {

    public GenericJsonParser() {
    }

    public HashMap<String, String> getJsonMap(String jsonflux) {

        String keyvalue;
        JsonParser parser = Json.createParser(new StringReader(jsonflux));
        JsonParser.Event event = parser.next();

        HashMap<String, String> jsonElements;
        jsonElements = new HashMap<String, String>();

        while (event != END_OBJECT) {
            event = parser.next();
            if (event == KEY_NAME) {
                keyvalue = parser.getString();
                System.out.println("KeyValue === " + keyvalue);
                parser.next();
                jsonElements.put(keyvalue, parser.getString());
            }
        }

        return jsonElements;
    }

}


IV- Run the application

The application will look like this when it is running :

Here a sample data we will save :

When  they click on the button Save they obtain this Json object (here captured by Firebug ) :

Published at DZone with permission of its author, Drabo Constantin.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Luis G. Moré replied on Tue, 2013/08/13 - 11:15am

Hello Mr. Constantin! I'm finding this tutorial really useful, I'm reading it indeed to learn ExtJS. Very good tutorial!

Bryan Copeland replied on Wed, 2013/08/14 - 7:18am

 Excellent article good sir!

I think especially the GenericJsonParser.java is an extremely useful utility for serializing JSON to Java objects (i.e HashMap here, but could also use similar conventions for Arrays, Lists or custom Bean Objects directly).

However, I didn't see where JSON-P came into play because the post of JSON data hjappened directly it seems like a great JSON API mechanism but maybe not JSON-P. Wouldn't that require one final step, such as an external site using a passthrough request to something like a Servlet or Spring request handler that supports a client-side callback of the requestor's specification?

Something like the following:
http://stackoverflow.com/questions/4683114/sending-jsonp-vs-json-data
http://stackoverflow.com/questions/2699277/post-data-to-jsonp

Drabo Constantin replied on Wed, 2013/08/14 - 9:05am in response to: Bryan Copeland

 Hello Bryan,

This a sentence mistake that brings confusion. You should read  Java API for JSON-P ( Json Procession refered to JSR #353) . JSR-353 provides  APIs that are based on the mechanism of JSON API.  I tried to be as close to this specification.

view sourceprint?1.Wouldn't that require one final step, such as an external site using a passthrough request to something like a Servlet or Spring request handler that supports a client-side callback of the requestor's specification?

It could be ! in this part of the serie of tutorials , I just treated the case from client-side to server. In a next article I will write on  client-side callbacks ( i.e data from database to populate  a datagrid).

I hope I have answered to your question. Thank you much for the feedbacks .

Constantin







Drabo Constantin replied on Wed, 2013/08/14 - 9:53am in response to: Luis G. Moré

 Thank Luis !

Robert Casey replied on Thu, 2013/08/15 - 11:45am

 Great tutorial article.  Code is nicely structured and easy to follow.

Muhammad Danial replied on Mon, 2014/03/31 - 8:06am

ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side. Fridge freezer repairs

Black Men replied on Fri, 2014/04/11 - 11:32am

 ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side. 

Greg Aziz

Black Men replied on Sun, 2014/04/13 - 1:03am

 It's no accident that at the same time industry lobbyists in Raleigh have convinced state legislators to limit state rules to the bare federal minimum, industry lobbyists in D.C. are trying to make the federal standards optional for states.

soundcloud downloader

Samad Khatri replied on Tue, 2014/04/15 - 10:11am in response to: Luis G. Moré

 World stem cell therapy in the USA and offshore are increasingly developing and soon will change the medical field we know. Parkinson’s disease 

Black Men replied on Wed, 2014/04/16 - 8:13am


 ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side. audio software

Black Men replied on Fri, 2014/04/18 - 1:20am

 ExtJs as client-side framework and Java web with Spring framework in server-side.  

how to teach your children to read

Black Men replied on Sat, 2014/04/19 - 6:16am

 ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side.

Jackie Dinh - Toronto SEO Consultant

Samad Khatri replied on Sat, 2014/04/19 - 10:03am in response to: Luis G. Moré

 Hello Mr. Constantin! I'm finding this tutorial really useful, I'm reading it indeed to learn ExtJS. Very good tutorial! https://www.rebelmouse.com 

Black Men replied on Sun, 2014/04/20 - 1:35am

 I enjoyed reading your post and found it to be informative and to the topic. Thank you for not rambling on and on just to fill the page. Thanks..     

http://aokmedia.co

Black Men replied on Mon, 2014/04/21 - 11:51pm

 ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side.

best matching jewelry
 

Black Men replied on Tue, 2014/04/22 - 2:09am

 But in expanding the program, Congress also transformed the program from one in which performance critieria were used to select which proposals most deserved tax dollars into a first-come-first-served pool that will no longer prioritize projects that provide the most public benefits.     

short term rentals

Black Men replied on Tue, 2014/04/22 - 6:06am

 While data enables understanding of things useful to the business, bigger isn’t necessarily always better. Data grows constantly and much of it is disposable. According to Gartner’s Yuen, the usefulness of data is defined by its relevance—but that relevance changes as time passes, he added.  

fibroidsmiracle.co.uk

Black Men replied on Tue, 2014/04/22 - 9:51am

 ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side. 

Blue Mountain Coffee

Black Men replied on Wed, 2014/04/23 - 3:13am

 In the case of a retailer wanting insight into its customers, it needs to make sense of its customers’ comments on social media networks, he said. “To do so, the retailer needs a text or sentiment analysis tool.”

cliquez ici

Black Men replied on Thu, 2014/04/24 - 4:01am

 A unique progra usiness idea from conception to reality. Students learn everything from how to estimating the target market of their entrepreneurial ideas to writing  pitching business plans.    

http://www.drewniana9.pl/

Black Men replied on Sat, 2014/04/26 - 8:26am

 Congress also transformed the program from one in which performance critieria were used to select which proposals most deserved tax dollars into a first-come-first-served pool that will no longer prioritize projects that provide the most public benefits.   

amway

Samad Khatri replied on Sat, 2014/04/26 - 11:44am in response to: Luis G. Moré

 Saturday morning with the junior racers, 20 years and younger taking to the courses first. Most ski races are two  novafaktoria.pl

Black Men replied on Sun, 2014/04/27 - 4:32am

 ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side. 

cooling measures government

Samad Khatri replied on Mon, 2014/04/28 - 12:33pm in response to: Bryan Copeland

 However, I didn't see where JSON-P came into play because the post of JSON data hjappened directly it seems like a great JSON API mechanism but maybe not JSON-P. Wouldn't that require one final step zyweploty.com

Samad Khatri replied on Tue, 2014/04/29 - 8:06am in response to: Bryan Copeland

 some blogs, seems a pretty nice platform you are using. I'm currently using Wordpress for a few of my sites but looking girlfriend system 

Samad Khatri replied on Wed, 2014/04/30 - 1:42pm in response to: Bryan Copeland

 Embedded Developer LLC, in cooperation with 21IC, China’s leading site for engineers, and 21IDH, the leading site for Independent Design Houses www.producentrolet.pl

Jakie Mac replied on Sat, 2014/05/03 - 5:06am

 Select your preferred way to display the comments and click "Save settings" to activate your changes.

melbourne pop top campers

Jakie Mac replied on Sun, 2014/05/04 - 8:22am

 In a previous article  I demonstrated how to build a ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side.

pop top campers in victoria

Black Men replied on Sat, 2014/05/10 - 5:53am

 

 ExtJs application. In the next lines I will show the content of a small patient management application using ExtJs as client-side framework and Java web with Spring framework in server-side.

parapharmacie en ligne

Samad Khatri replied on Thu, 2014/05/22 - 6:50am

Congress also transformed the program from one in which performance critieria were used to select which proposals most deserved tax dollarsdoniczkidoogrodu.pl

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.