ExtJs 4 Ajax Request and Response example using Java Servlet and JSON

AJAX stand for Asynchronous JavaScript and XML. AJAX is not a technology in itself, it is a way of developing Web applications that combines: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and the most importantly XMLHttpRequest object.

When these technologies are combined in the AJAX model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page making sites faster. Also AJAX is asynchronous, so you can run processes in background that can update the UI without any user interaction.

Although X in AJAX stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in AJAX model. This example of AJAX request uses JSON, ExtJs JavaScript framework and Java Servlet on the backend. Here we have created a simple Login form that will take a userId and password and then make an AJAX request to validate the request.


ExtJs 4 Ajax JSON Request and Response example using Java Servlet
ExtJs 4 Ajax JSON Request and Response example using Java Servlet
ExtJs 4 Ajax JSON Request and Response example using Java Servlet

Our application HTML file - index.html

<html>
<head>
    <title>ExtJs 4 Ajax Request and Response Example</title>

    <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
    <script type="text/javascript" src="extjs/ext-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>

</head>
<body></body>
</html>

Our application Javascript file - apps.js

Ext.Loader.setConfig({ 
    enabled: true 
    });

Ext.application({
    name: 'MyAjaxApp',

    appFolder: 'app',
   
    controllers: [
                  'AjaxExample'
              ],

    launch: function() {
        Ext.create('Ext.container.Viewport', {
            items: [
                {
                    xtype: 'ajaxRequestForm',
                }
            ]
        });
    }
});

Javascript source for Login form - AjaxRequestForm.js

Ext.define('MyAjaxApp.view.AjaxRequestForm', {
    extend: 'Ext.form.Panel',
    alias : 'widget.ajaxRequestForm',
    width: 500,
    frame: true,
    title: 'ExtJs Ajax Request Example',
    bodyPadding: '10 10 0',

    defaults: {
        anchor: '100%',
        allowBlank: false,
        msgTarget: 'side',
        labelWidth: 75
    },

    items: [{
        xtype: 'textfield',
        name: 'userId',
        fieldLabel: 'User Id'
    },{
        xtype: 'textfield',
        name: 'password',
        fieldLabel: 'Password',
        inputType: 'password',
    }],

    buttons: [{
        text: 'Submit',
        action: 'login'
    },
    {
        text: 'Reset Form',
        handler: function() {
            this.up('form').getForm().reset();
        }
    }]
});

Javascript source for ExtJs controller - AjaxExample.js

Ext.define('MyAjaxApp.controller.AjaxExample', {
            extend : 'Ext.app.Controller',

            //define the views
            views : ['AjaxRequestForm'],

            //special method that is called when your application boots
            init : function() {
               
                //control function makes it easy to listen to events on 
                //your view classes and take some action with a handler function
                this.control({
                   
                            //when the viewport is rendered
                            'viewport > panel' : {
                                render : this.onPanelRendered
                            },
                            //when you click Submit button
                            'ajaxRequestForm button[action=login]' : {
                                click : this.onLoginRequest   
                            }
                    });
            },

            onPanelRendered : function() {
                //just a console log to show when the panel is rendered
                console.log('The panel was rendered');
            },
           
            onLoginRequest : function(button) {
                //just a console log to show when the Login Ajax request starts
                console.log('Login Ajax Request in progress');
                               
                var form = button.up('form').getForm();
                if(form.isValid()){
                   //create an AJAX request
                    Ext.Ajax.request({
                        url : 'Login',
                        method:'POST', 
                        params : {
                            loginData: Ext.encode(form.getValues())
                        },
                        scope : this,
                        //method to call when the request is successful
                        success : this.onLoginSuccess,
                        //method to call when the request is a failure
                        failure : this.onLoginFailure
                }); 
                }
            },
           
            onLoginFailure : function(err) {
                //Alert the user about communication error
                Ext.MessageBox.alert('Error occured during Login', 'Please try again!');
            },

            onLoginSuccess : function(response, opts) {
                //Received response from the server
                response = Ext.decode(response.responseText);
                if(response.success){
                    Ext.MessageBox.alert('Successful Login', response.message);
                }
                else {
                    Ext.MessageBox.alert('Login failed', response.message);
                }
        }
    });

Ext.Ajax.request parameters

  • url
    • The URL to which to send the request, or a function to call which returns a URL string.
  • params
    • An object containing properties which are used as parameters to the request, a url encoded string or a function to call to get either.
  • method
    • The HTTP method to use for the request. Defaults to the configured method, or if no method was configured, "GET" if no parameters are being sent, and "POST" if parameters are being sent.
  • success
    • The function to be called upon success of the request. The following parameters are passed to this function
      • response: The XMLHttpRequest object containing the response data.
      • option: The parameter to the request call.
  • failure
    • The function to be called upon success of the request. The following parameters are passed to this function
      • response: The XMLHttpRequest object containing the response data.
      • options: The parameter to the request call.


ExtJs 4 Ajax JSON Request and Response example using Java Servlet
ExtJs 4 Ajax JSON Request and Response example using Java Servlet

Java Object source for our user Information - UserInfo.java

package com.as400samplecode;

public class UserInfo {
   
    String userId = null;
    String password = null;
   
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

   
}

Java Servlet source for validating user Information - Login.java

package com.as400samplecode;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Login() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String loginData = request.getParameter("loginData");
        Gson gson = new Gson();
        UserInfo userInfo = gson.fromJson(loginData, UserInfo.class);
        String userId = userInfo.getUserId();
        String password = userInfo.getPassword();

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");

        JsonObject myObj = new JsonObject();

        //nothing was sent   
        if(userId == null || password == null){
            myObj.addProperty("success", false);
            myObj.addProperty("message", "Please send userId and Password!");
        }
        else {
            if(userId.trim().equals("ajax") && password.trim().equals("request")){
                myObj.addProperty("success", true);
                myObj.addProperty("message", "Welcome to as400sampecode.blogspot.com");
            }
            else {
                myObj.addProperty("success", false);
                myObj.addProperty("message", "Looks like you forgot your login infomartion");
            }
        }
       
        out.println(myObj.toString());
        out.close();
    }
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.