Monday, October 8, 2012

Template Example Code

String msg = "Hello {0} Please find attached {1} which is due on {2}";
String[] values = {
  "John Doe", "invoice #123", "2009-06-30"
};
System.out.println(MessageFormat.format(msg, values));

===================
String template = "Hello %s Please find attached %s which is due on %s";

String message = String.format(template, name, invoiceNumber, dueDate);



http://www.tutorialspoint.com/log4j/index.htm

Multi Language Js file for i18n

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

Ext.Loader.setPath('Ext.ux', '../ux/');

Ext.require([
    'Ext.data.*',
    'Ext.tip.QuickTipManager',
    'Ext.form.*',
    'Ext.ux.data.PagingMemoryProxy',
    'Ext.grid.Panel'
]);

Ext.onReady(function(){
    MultiLangDemo = (function() {
        // get the selected language code parameter from url (if exists)
        var params = Ext.urlDecode(window.location.search.substring(1));
        //Ext.form.Field.prototype.msgTarget = 'side';
               
        return {
            init: function() {
                Ext.tip.QuickTipManager.init();
           
                /* Language chooser combobox  */
                var store = Ext.create('Ext.data.ArrayStore', {
                    fields: ['code', 'language', 'charset'],
                    data : Ext.exampledata.languages // from languages.js
                });
               
                var combo = Ext.create('Ext.form.field.ComboBox', {
                    renderTo: 'languages',
                    store: store,
                    displayField:'language',
                    queryMode: 'local',
                    emptyText: 'Select a language...',
                    hideLabel: true,
                    listeners: {
                        select: {
                            fn: function(cb, records) {
                                var record = records[0];
                                window.location.search = Ext.urlEncode({"lang":record.get("code"),"charset":record.get("charset")});
                            },
                            scope: this
                        }
                    }
                });
       
                if (params.lang) {
                    // check if there's really a language with that language code
                    var record = store.findRecord('code', params.lang, null, null, null, true);
                    // if language was found in store assign it as current value in combobox
                    if (record) {
                        combo.setValue(record.data.language);
                    }
                }           
           
                if (params.lang) {
                    var url = Ext.util.Format.format("../../locale/ext-lang-{0}.js", params.lang);
               
                    Ext.Ajax.request({
                        url: url,
                        success: this.onSuccess,
                        failure: this.onFailure,
                        scope: this
                    });
                } else {
                    this.setupDemo();
                }
            },
            onSuccess: function(response, opts) {
                eval(response.responseText);
                this.setupDemo();
            },
            onFailure: function() {
                Ext.Msg.alert('Failure', 'Failed to load locale file.');
                this.setupDemo();
            },
            setupDemo: function() {
                /* Email field */
                Ext.create('Ext.FormPanel', {
                    renderTo: 'emailfield',
                    labelWidth: 100, // label settings here cascade unless overridden
                    frame: true,
                    title: 'Email Field',
                    bodyStyle: 'padding:5px 5px 0',
                    width: 380,
                    defaults: {
                        msgTarget: 'side',
                        width: 340
                    },
                    defaultType: 'textfield',
                    items: [{
                        fieldLabel: 'Email',
                        name: 'email',
                        vtype: 'email'
                    }]
                });
           
                /* Datepicker */
                Ext.create('Ext.FormPanel', {
                    renderTo: 'datefield',
                    labelWidth: 100, // label settings here cascade unless overridden
                    frame: true,
                    title: 'Datepicker',
                    bodyStyle: 'padding:5px 5px 0',
                    width: 380,
                    defaults: {
                        msgTarget: 'side',
                        width: 340
                    },
                    defaultType: 'datefield',
                    items: [{
                        fieldLabel: 'Date',
                        name: 'date'
                    }]
                });
           
                // shorthand alias               
                var monthArray = Ext.Array.map(Ext.Date.monthNames, function (e) { return [e]; });
                var ds = Ext.create('Ext.data.Store', {
                     fields: ['month'],
                     remoteSort: true,
                     pageSize: 6,
                     proxy: {
                         type: 'pagingmemory',
                         data: monthArray,
                         reader: {
                             type: 'array'
                         }
                     }
                 });
                            
                 Ext.create('Ext.grid.Panel', {
                     renderTo: 'grid',
                     width: 380,
                     height: 203,
                     title:'Month Browser',
                     columns:[{
                         text: 'Month of the year',
                         dataIndex: 'month',
                         width: 240
                     }],
                     store: ds,           
                     bbar: Ext.create('Ext.toolbar.Paging', {
                             pageSize: 6,
                             store: ds,
                             displayInfo: true
                     })
                 });
           
                // trigger the data store load
                ds.load();           
            }
        };
   
    })();
    MultiLangDemo.init();
});

Json Codes

 buttonJson

function extjsfunc(){

Ext.require([
    'Ext.tab.*'
    ,'Ext.window.*'
    ,'Ext.tip.*'
    ,'Ext.layout.container.Border'
    ,'Ext.window.MessageBox'   
    ,'Ext.grid.*'
    ,'Ext.data.*'
    ,'Ext.util.*'
    ,'Ext.state.*'
    ,'Ext.form.*'
]);
Ext.onReady(function(){

Ext.define('model_1',{
      extend:'Ext.data.Model',
      fields:[
              {name: 'name'},
                {name: 'dept'},          
                {name: 'opchrg'},
             ]
   });
var store = new Ext.data.JsonStore({
    proxy: {
        url: 'getJson.jsp',
        type: 'ajax',
        reader: {
            type: 'json',
            root: 'model_1'
        }
    },
    fields: ['name', 'dept','opchrg']
});

     // create the grid
 var grid = new Ext.grid.GridPanel({
        store: store,
        columns: [
            //{id:'id',header: 'ID', width: 30, sortable: true, dataIndex: 'id'},
            {header: "Name", width: 60, dataIndex: 'name', sortable: true},
            {header: "Dept", width: 60, dataIndex: 'dept', sortable: true},
            {header: "Opchrg", width: 60, dataIndex: 'opchrg', sortable: true},
        ],
        renderTo:'editor-grid',
        width:540,
        height:200
    });

});

}

</script>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script>
        // use the scoped CSS stylesheet if the url has a scopecss parameter
      document.write('<link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all' +
            ((window.location.search.indexOf('scopecss') === -1) ? '' : '-scoped') + '.css" />');  
    </script>
   <link rel="stylesheet" type="text/css" href="extjs/shared/example.css" />
   <link rel="stylesheet" type="text/css" href="extjs/ux/css/CheckHeader.css" /> 
    <!--<script type="text/javascript" src="library/ext-all.js"></script> -->
    <script type="text/javascript" src="library/ext-all-debug.js"></script>
</head>    
<input type ="button" id="srchbtn" onclick="extjsfunc()" class="extra" value="Search">

<div id="editor-grid"></div>



getJson:

<%@page import="db.*"%>
<%@page import="org.json.JSONArray"%>
<%@page import="java.io.PrintWriter"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
   <%
                    str = "SELECT * FROM dept1";
                   
                    dept objdept = new dept();
                    String ar_rs[] = objdept.displayValue(str);
                    JSONArray jsonObj=new JSONArray();
                    int i=0;
                    while(i< ar_rs.length)
                    {
                        jsonObj.put(i,ar_rs[i]);
                        i++;
                    }
                    out.println(jsonObj);
                
        %>
    

Servlets with Extjs

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


    public class register extends HttpServlet{

    Statement ps1 = null;
      ResultSet rs1 = null;           

   public void doPost(HttpServletRequest request, HttpServletResponse response)
                                   throws ServletException,IOException{
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();

     System.out.println("MySQL Connect Example.");
    Connection conn = null;
    String url        = "jdbc:mysql://localhost:3306/";
    String dbName   = "user_register";
    String driver   = "com.mysql.jdbc.Driver";
    String userName = "";
    String password = "";

    String username = request.getParameter("username");
    String user_pass = request.getParameter("password");
    String firstname = request.getParameter("firstname");
    String lastname = request.getParameter("lastname");
    String email = request.getParameter("email");
    String state = request.getParameter("state");
    String city = request.getParameter("city");
    String country = request.getParameter("country");
    Statement st;
    try {
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
      String query = "insert into register set

username='"+username+"',password='"+user_pass+"',firstname='"+firstname+"',lastname='"+lastname+"',email=

'"+email+"',state='"+state+"',city='"+city+"',country='"+country+"'";
       st = conn.createStatement();
       int i = st.executeUpdate(query);

      if(i>0)
        {
                pw.println("<html>");
                pw.println("<Title>");
                pw.println("Register");
                pw.println("</Title>");
                pw.println("<body>");
                pw.println("<table width='100%' align='center'>");
                pw.println("<tr>");
                pw.println("<td width='100%' align='center'

style='padding-top:100px;font-weight:bold;color:blue;'>");
                pw.println("You are Successfully entered the Record.");
                pw.println("</td>");
                pw.println("</tr>");
                pw.println("</table>");
                pw.println("</body>");
                pw.println("</html>");

        }
        else
        {
                  response.sendRedirect("register.html?error");
        }
    //  pw.println(query);

    String query1="select * from register";
        ps1 = conn.prepareStatement(query1);
        rs1 = ps1.executeQuery(query1);

/*Table for displaying the records */       

pw.println("<br>");
            pw.println("<b></b>");
            pw.println("<html><table border=''><tr>");
            pw.println("<td><b>Id</b></td>");
            pw.println("<td><b>Username</b></td>");
            pw.println("<td><b>First Name</b></td>");
            pw.println("<td><b>Last Name</b></td>");
            pw.println("<td><b>Email</b></td>");
            pw.println("<td><b>State</b></td>");
            pw.println("<td><b>City</b></td>");
            pw.println("<td><b>Country</b></td>");
            pw.println("</tr>");
            /*while(rs1.next())

            {
                Integer id        = rs1.getInt(1);
                String uname        = rs1.getString(2);
                String fname        = rs1.getString(4);
                String lname        = rs1.getString(5);
                String emailid     = rs1.getString(6);
                String statename   = rs1.getString(7);
                String cityname       = rs1.getString(8);
                String countryname = rs1.getString(9);
               
                pw.println("<tr>");
                pw.println("<td>"+id+"</td>");
                pw.println("<td>"+uname+"</td>");
                pw.println("<td>"+fname+"</td>");
                pw.println("<td>"+lname+"</td>");
                pw.println("<td>"+emailid+"</td>");
                pw.println("<td>"+statename+"</td>");
                pw.println("<td>"+cityname+"</td>");
                pw.println("<td>"+countryname+"</td>");
                pw.println("</tr>");
            }

            pw.println("</table><br>");*/
           

        JSONArray jArray = new JSONArray();
        while(rs1.next())

        {
                Integer id        = rs1.getInt(1);
                String uname        = rs1.getString(2);
                String fname        = rs1.getString(4);
                String lname        = rs1.getString(5);
                String emailid     = rs1.getString(6);
                String statename   = rs1.getString(7);
                String cityname       = rs1.getString(8);
                String countryname = rs1.getString(9);
   
                JSONObject jobj    = new JSONObject();

            //    jobj.put("id",id);
                jobj.put("uname",uname);
                jobj.put("fname",fname);
                jobj.put("lname",lname);
                jobj.put("emailid",emailid);
                jobj.put("statename",statename);
                jobj.put("cityname",cityname);
                jobj.put("countryname",countryname);

                jArray.add(jobj);
           
                       
        }
       
        //pw.println(jArray);       
    
     JSONObject jObjDevice = new JSONObject();
        jObjDevice.put("device", jArray);
        JSONObject jObjDeviceList = new JSONObject();
        jObjDeviceList.put("devicelist", jObjDevice );
   
        pw.println(jObjDevice);
       
      

 
      conn.close();
         pw.println("Disconnected from database");
    }     catch (Exception e)
    {
                e.printStackTrace();
        }
  }
}




var store_company = new Ext.data.Store({
          model: 'Company',
          proxy: {
              type: 'ajax',
              url: 'register',
              actionMethods: {create: "POST", read: "POST", update: "POST", destroy: "POST"},
              reader: {
                  type: 'json',
                  root: 'device',
                  success:'true'
              },
             
          }
         
       });



<script type="text/javascript">
   
    Ext.onReady(function() {              
       Ext.define('Company', {
           extend: 'Ext.data.Model',
           fields: [
                    {name:'uname',type: 'string'},
                    {name:'fname',type: 'string'},
                    {name:'lname',type: 'string'},
                    {name:'emailid',type: 'string'},
                    {name:'statename',type: 'string'},
                    {name:'cityname',type: 'string'},
                    {name:'country',type: 'string'}]
       });

       var store_company = new Ext.data.Store({
          model: 'Company',
          proxy: {
              type: 'ajax',
              url: 'register.class',    //Not sure if this is correct url:'register.class'"!!
             
              reader: {
                  type: 'json',
                  root:'device'
              },
             
          }
         
       });                            
       
       
        var grid_company = Ext.create('Ext.grid.Panel', {
                                     
            store: store_company,
               
                columns:[
                    
                {
                    text     : 'User Name',
                    width    : 120,
                    sortable : true,
                   
                    dataIndex: 'uname'
                },
                {
                    text     : 'Firstname',
                    width    : 120,
                    sortable : true,
                    dataIndex: 'fname'
                },
                {
                    text     : 'Lastname',
                    width    : 110,
                    sortable : true,
                    dataIndex: 'lname'
                },
                {
                    text     : 'Email',
                    width    : 150,
                    sortable : true,
                    dataIndex: 'emailid'
                },
                {
                    text     : 'State',
                    width    : 100,
                    sortable : true,
                    dataIndex: 'statename'
                },
                {
                    text     : 'City',
                    width    : 150,
                    sortable : true,
                    dataIndex: 'cityname'
                },
                {
                    text     : 'Country',
                    width    : 150,
                    sortable : true,
                    dataIndex: 'countryname'
                }
            ],
             bbar: Ext.create('Ext.PagingToolbar', {
        store: store_company,
        displayInfo: true,
        displayMsg: 'Displaying topics {0} - {1} of {2}',
        emptyMsg: "No topics to display"
    }),   
            height: 210,
            width: 902,
            title: 'Company List',
            renderTo: 'grid-company',
            viewConfig: {
                        stripeRows: true
                }       
        });
        store_company.load();
    });
    </script>

Myeclipse Key generator code in java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;

public class MyEclipseKeyGen {
    private static final String LL = "Decompiling this copyrighted software is a violation of both your license agreement and the Digital Millenium Copyright Act of 1998 (http://www.loc.gov/copyright/legislation/dmca.pdf). Under section 1204 of the DMCA, penalties range up to a $500,000 fine or up to five years imprisonment for a first offense. Think about it; pay for a license, avoid prosecution, and feel better about yourself.";

    public String getSerial(String userId, String licenseNum, String type) {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, 1000);
        //cal.add(6, -1);
        java.text.NumberFormat nf = new java.text.DecimalFormat("000");
        licenseNum = nf.format(Integer.valueOf(licenseNum));
        String verTime = new StringBuilder("-").append(
                new java.text.SimpleDateFormat("yyMMdd").format(cal.getTime()))
                .append("0").toString();
        String need = new StringBuilder(userId.substring(0, 1)).append(type)
                .append("300").append(licenseNum).append(verTime).toString();
        String dx = new StringBuilder(need).append(MyEclipseKeyGen.LL).append(
                userId).toString();
        int suf = this.decode(dx);
        String code = new StringBuilder(need).append(String.valueOf(suf))
                .toString();
        return this.change(code);
    }

    private int decode(String s) {
        int i;
        char[] ac;
        int j;
        int k;
        i = 0;
        ac = s.toCharArray();
        j = 0;
        k = ac.length;
        while (j < k) {
            i = (31 * i) + ac[j];
            j++;
        }
        return Math.abs(i);
    }

    private String change(String s) {
        byte[] abyte0;
        char[] ac;
        int i;
        int k;
        int j;
        abyte0 = s.getBytes();
        ac = new char[s.length()];
        i = 0;
        k = abyte0.length;
        while (i < k) {
            j = abyte0[i];
            if ((j >= 48) && (j <= 57)) {
                j = (((j - 48) + 5) % 10) + 48;

            } else if ((j >= 65) && (j <= 90)) {
                j = (((j - 65) + 13) % 26) + 65;

            } else if ((j >= 97) && (j <= 122)) {
                j = (((j - 97) + 13) % 26) + 97;
            }
            ac[i] = (char) j;
            i++;
        }
        return String.valueOf(ac);
    }

    public MyEclipseKeyGen() {
        super();
    }

    public static void main(String[] args) {
        try {
            // MyEclipse Standard Subscription --------- YE2MY
            // MyEclipse Professional Subscription ---- YE3MP
            // MyEclipse Blue Subscription --------------- YE3MB
            // MyEclipse for Spring Subscription -------- YE3MS
            String type = "YE3MB-";
            // for the local version of String type ="YE3MP-";//??????
            System.out.println("please input register name:");
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    System.in));
            String userId = null;
            userId = reader.readLine();
            MyEclipseKeyGen myeclipsegen = new MyEclipseKeyGen();
            String res = myeclipsegen.getSerial(userId, "5", type);
            System.out.println("Serial:" + res);
            reader.readLine();
        } catch (IOException ex) {
        }
    }

}

Key
====

oLR8ZO-855550-6052505603586246

Extjs i18n

http://gaver.dyndns.org/elmasse/site/index.php/blog/4-posts/10-i18nbundle-resource-bundle-extjs-extension-



Ext.i18n.bundle - Resource Bundle ExtJS extension




This is a Resource Bundle implementation for ExtJS. What's a Resource Bundle? This idea comes from Java world where you can separate all the locale based information from the source code. This helps to maintain the source code and facilitates the translations.
In this version of Ext.i18n.Bundle you can store only Strings. A Bundle file is a properties file where you store your key-value pairs. Every bundle has a hierarchical naming structure based on the language selected. Let's take for example a bundle named 'Application', the Ext.i18n.Bundle component will try to find first the specific language file. If no language is specified, it will guess the language based on the browser settings. Let's assume that your browser language is english US, so the bundle file name will be

Application_en-US.properties

If that file doesn't exists, it will try to load the default file:

Application.properties

Note: For those who are familiar with Java Resource Bundles, this is not exactly the same implementation. This component will only load one properties file. This means that if you don't store a key-value in the loaded file it wont be searched from the parent file, which is the behavior in Java.

Implementation

Constructor
The Ext.i18n.Bundle has a few parameters in the constructor. Most of them are optional.

Ext.i18n.Bundle(config)

config:

    bundle: {String} the bundle name.
    path: {String} the uri to the resource folder where the properties files are stored. Optional.
    lang: {String} the language code. It must be in the format xx-YY where xx specifies the 2 character language code (lowercase) and YY is the 2 characters country code (uppercase). Example: 'en-US'. Optional. Default to the browser language.
    method: {String} the method used by the HttpProxy to retrieve the files. Optional. Default to 'GET'.



Methods
Ext.i18n.Bundle has a few methods.

onReady(function)
This method must be executed in order to get access to the bundle. All the code that need to access to the bundle must be executed into the function.

    function: {Function} The function that contains all the code that will reference to bundle.



getMsg(key)
This method returns the content associated with the passed key. If the key cannot be found then it returns {key}.undefined

    key: {String} the bundle key



Let's see an example

In this example I will show you the basic usage of the component. You can find this example code into the zip file with the sources.
    Ext.onReady(function(){
        var bundle = new Ext.i18n.Bundle({bundle:'Application', path:'resources'}); //#1
        bundle.onReady(function(){
   
            var panel = new Ext.Panel({
                renderTo: 'panelTest',
                title: bundle.getMsg('panel.title'),  //#2
                height: 300,
                width: 800,
                html: bundle.getMsg('panel.html') //#3
            });
            
        }); //bundle.onReady
    });

In this code we create the bundle component associated with 'Application' bundle file. At #1 we just defined the bundle name and the path where we store or expose our properties files. In this case the files will be loaded from http://{your.domain}/resources . If the browser language is en-US, then the resources/Application_en-US.properties file will be loaded. And, if it cannot be found, then resources/Application.properties file will be loaded.
My Application_en-US.properties looks like:

panel.title "'panel title with quotes'"
panel.html "Something goes here!"

As you can see I defined 2 key values: panel.title and panel.html. Once the file is loaded then the onReady method is executed. At this point I can access the file content. I show in #2 and #3 how to retrieve the key content.

Some considerations

First, you need to execute this code from a web container. It cannot be executed locally since we are using an HttpProxy.
Second, all the bundlelized messages will be available inside the Ext.i18n.Bundle.onReady method. This means that you can use the bundle inside that method. But, you can also use it if you define your classes in separate js files. The only restriction is that the code must be called from the onReady function. Let me show you an example:
    // Main.js
    Ext.onReady(function(){
            
        var bundle = new Ext.i18n.Bundle({bundle:'Application', path:'resources'});
        bundle.onReady(function(){
   
            var panel = new MyPanel();
            
        }); //bundle.onReady
    });
   
    //MyPanel.js
    MyPanel = function(config){
            MyPanel.superclass.constructor.call(this,{
                renderTo: 'panelTest',
                title: bundle.getMsg('panel.title'),
                height: 300,
                width: 800,
                html: bundle.getMsg('panel.html')
            });
    };
    Ext.extend(MyPanel, Ext.Panel);

This is a correct usage of the bundle component. But, if you try to use the bundle reference into a prototype definition you will get an undefined reference.
    //MyPanel.js
   
    MyPanel = Ext.extend(Ext.Panel, {
        title: bundle.getMsg('panel.title')
        //other prototype definitions...
    });
Here javascript will evaluate the bundle variable at parsing time, and there bundle is undefined yet, so you cannot access it. Anyway, if the bundle variable were defined at that time, it will not retrieve the key content until the file is loaded, which occurs inside the onReady method.

Download the code and example

Go to Downloads section in the Main Menu.




Last weekend I was working on i18n with Ext.js, and there is a feature that I miss (so much) from jsp and it is the Resource Bundle. So I realized that I should get something similar to this and I started to write an Ext.i18n.ResourceBundle. The main idea is to create an object that can get a bundle, it means that taking the resource bundle, i.e. from a resource name and the browser's language it tries to find a .properties, so if the language is es-ES it looks for the [bundle]_es-ES.properties file and if it does not exist then it reads the [bundle].properties.

Then you can get a message by the key property through the getMsg(key) method.
This is the entire code and a little example. Enjoy it!

Code and Example could be found here


Usage:

var bundle = new Ext.i18n.Bundle({bundle='Application'});
bundle.onReady(
alert('example'+ bundle.getMsg('key1'));
);

This would read:
-An Application_es-ES.properties file like this if the browser's language is es-ES:
#This is a simple comment
key1 "Mensaje para la propiedad key1"


-If the Application_es-ES.properties doesn't exist then tries to find the Application.properties file like this:
#This is a simple comment
key1 "this is the message for key1"

Bundle(config): config: {bundle: , resource:}
bundle: The bundle name for the properties file.
{bundle: 'mybundle'}
This looks for the file located in:
http:/yourdomain/yourApp/mybundle_[language].properties.
You will need at least the mybundle.properties file.


path: (optional) the path to the bundle file.
{bundle: 'mybundle, path: 'resources'}
This looks for the file located in:
http:/yourdomain/yourApp/resources/mybundle_[language].properties.


Take into account that you need to write your application in the bundle.onReady() method in order to be able to access to your bundle.

Extjs with java integration

Here is my scenerio:
I had 2 pages.
1) Login page which is designed using the FormPanel - Used to authenticate user.(Added in the above post)
2) Home page containing extjs Basic Grid showing all the existing users.
Grid page

Form
Code:

         Ext.onReady(function(){

    var simple = new Ext.form.FormPanel({

        standardSubmit: true,

        frame:true,
        title: 'Login',
        width: 350,
        defaults: {width: 230},
        defaultType: 'textfield',
        items: [{
                fieldLabel: 'Username',
                name: 'username',
                id: 'username',
                allowBlank:false
            },
            {
                fieldLabel: 'Password',
                name: 'password',
               inputType:'password',
                allowBlank:false
            },
           
            {
                inputType: 'hidden',
                id: 'submitbutton',
                name: 'myhiddenbutton',
                value: 'hiddenvalue'
            }

        ],
        buttons: [{
            text: 'Submit',
            handler: function() {
            simple.getForm().getEl().dom.action = 'ValidationServlet';
            simple.getForm().getEl().dom.method = 'POST';
            simple.getForm().submit({
                            /*Success and Failure functions*/
                         
                            success:function(){
                            Ext.Msg.prompt('Status', 'Login Successful!', function(btn, text){
                   if (btn == 'ok'){
                                        var redirect = 'success.html';
                                     window.location = redirect;
                                   }
                    });
             
},

            // Failure function, see comment above re: success and failure.
            // You can see here, if login fails, it throws a messagebox
            // at the user telling him / her as much. 

                        failure:function(form, action){
                            if(action.failureType == 'server'){
                                obj = Ext.util.JSON.decode(action.response.responseText);
                                Ext.Msg.alert('Login Failed!', obj.errors.reason);
                            }else{
                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText);
                            }
                            simple.getForm().reset();
                        }
                                   
                                   
                                   
                                    });
            }
        }]


    });
    simple.render('mydiv');

});

And my servlet code is :
Code:

String result;
                            if ((nodeName.item(0).getChildNodes().item(0).getNodeValue().equals(user))&&(nodeGrade.item(0).getChildNodes().item(0).getNodeValue().equals("A")))
                            {   
                             
                                result="{success:true}";
                            }
                            else
                            {   
                                result = "{success:false,errors:{reason:'Login failed.Try again'}}";
                               
                                }   
                           
                            pw.println(result);

Here I print the JSON result on success and failure.They get printed based on conditions correctly.
But,when I run the application it just prints the json result instead of returning it back to the success/failure function in the js file.

Grid page
Code:

Ext.onReady(function() {
                /*Tree panel*/
               
    var treePan=Ext.create('Ext.tree.Panel', {
    id:'candTree',
    renderTo: 'tree',
    title: 'Simple Tree',
    width: 200,
    height: 300,
    useArrows:true,
   
    frame: true,
   
    root: {
        text: 'Root',
        expanded: true,
       
        children: [
            {
                text: 'Child 1',
                id:'CH1',
                leaf: true
            },
            {
                text: 'Child 2',
                id:'CH2',
                leaf: true
            },
            {
                text: 'Child 3',
                expanded: true,
                children: [
                    {
                        text: 'Grandchild',
                        leaf: true
                    }
                ]
            }
        ]
    }
});


/*Handling tree Events*/

        treePan.getSelectionModel().on('select', function(selModel, record) {
       
        if (record.get('leaf')) {
            //Ext.getCmp('candGrid').layout.setActiveItem(record.getId() + '-panel');
           
            if(record.getId()=='CH1')
            {
            //window.alert('THis is'+record.getId() +'-panel');
            Ext.define('Company', {
           extend: 'Ext.data.Model',
           fields: [
                    {name:'uname',type: 'string'},
                    {name:'fname',type: 'string'},
                    {name:'lname',type: 'string'},
                    {name:'emailid',type: 'string'},
                    {name:'statename',type: 'string'},
                    {name:'cityname',type: 'string'},
                    {name:'countryname',type: 'string'}]
       });

       var store_company = new Ext.data.Store({
          model: 'Company',
          proxy: {
              type: 'ajax',
              url: 'register',
                actionMethods: {create: "POST", read: "POST", update: "POST", destroy: "POST"},
              reader: {
                  type: 'json',
                  root: 'device',
                  success:'true'
              },
             
          }
         
       });                           
       
       
        var grid_company = Ext.create('Ext.grid.Panel', {
                                     
            store: store_company,
               
                columns:[                   
                {
                    text     : 'User Name',
                    width    : 120,
                    sortable : true,
                   
                    dataIndex: 'uname'
                },
                {
                    text     : 'Firstname',
                    width    : 120,
                    sortable : true,
                    dataIndex: 'fname'
                },
                {
                    text     : 'Lastname',
                    width    : 110,
                    sortable : true,
                    dataIndex: 'lname'
                },
                {
                    text     : 'Email',
                    width    : 150,
                    sortable : true,
                    dataIndex: 'emailid'
                },
                {
                    text     : 'State',
                    width    : 100,
                    sortable : true,
                    dataIndex: 'statename'
                },
                {
                    text     : 'City',
                    width    : 150,
                    sortable : true,
                    dataIndex: 'cityname'
                },
                {
                    text     : 'Country',
                    width    : 150,
                    sortable : true,
                    dataIndex: 'countryname'
                }
            ],
             bbar: Ext.create('Ext.PagingToolbar', {
        store: store_company,
        displayInfo: true,
        displayMsg: 'Displaying topics {0} - {1} of {2}',
        emptyMsg: "No topics to display"
    }),   
            id:'candGrid',
            height: 300,
            width: 902,
            title: 'Company List',
            region:'center',
            renderTo: 'grid-company',
            viewConfig: {
                        stripeRows: true
                }       
        });
                store_company.load();
        }
       
        /*Second tree item value grid-Contains details of the users*/       
       
    }//If closed here
    });
});

Individually these pages are well displayed.

Now i want to integrate these pages. Once the user is authenticated in login page i want to display the home page. So how to redirect or display the home page in extjs??

I have used servlets at the backend(I am not familiar with frameworks).Instead of the grid page t displays the JSON result for the grid.

I hope to get some help now.

his is the code from my Validation servlet(works fine standalone).the callbacks are working
Code:

       if (checkUser=="1")
                        {
                              //Valid user
                                result="{success:true}";
                              
                        }
                        else
                        {       
                                res.sendRedirect("failure.html");
                                //pw.println("Invalid user");
                        }
                       
                        pw.println(result);

The callback function is.
Code:

    success:function(form,action){
                           
                                alert('Status', 'Login Successful!', function(btn, text){
                   if (btn == 'ok'){
                                var redirect = 'grid.html';
                                window.location = redirect;
                                   }
                    });
                            },

                    failure:function(form, action){
                            if(action.failureType == 'server'){
                                obj = Ext.util.JSON.decode(action.response.responseText);
                                Ext.Msg.alert('Login Failed!', obj.errors.reason);
                            }else{
                                Ext.Msg.alert('Warning!',  'Authentication server is unreachable : ' +  action.response.responseText);
                            }

But,here in the callback I want it to redirect it to the grid.html(A page where I display a grid).
Instead of redirecting it goes in the failure part and prints the JSON returned by the 2nd servlet(which fetches grid data.).This connects to the database and returns json.What want is on success the page to be redirected to the grid page and display the grid with content.

The second servlet:

Code:

   import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


    public class register extends HttpServlet{

    Statement ps1 = null;
      ResultSet rs1 = null;           

   public void doPost(HttpServletRequest request, HttpServletResponse response)
                                   throws ServletException,IOException{
    response.setContentType("application/json");
    PrintWriter pw = response.getWriter();

     System.out.println("MySQL Connect Example.");
    Connection conn = null;
    String url        = "jdbc:mysql://localhost:3306/";
    String dbName   = "user_register";
    String driver   = "com.mysql.jdbc.Driver";
    String userName = "";
    String password = "";
   
    try {
      Class.forName(driver).newInstance();
      conn = DriverManager.getConnection(url+dbName,userName,password);
      System.out.println("Connected to the database");
    
    //  pw.println(query);

    String query1="select * from register";
        ps1 = conn.prepareStatement(query1);
        rs1 = ps1.executeQuery(query1);
           

        JSONArray jArray = new JSONArray();
        while(rs1.next())

        {
                Integer id        = rs1.getInt(1);
                String uname        = rs1.getString(2);
                String fname        = rs1.getString(4);
                String lname        = rs1.getString(5);
                String emailid     = rs1.getString(6);
                String statename   = rs1.getString(7);
                String cityname       = rs1.getString(8);
                String countryname = rs1.getString(9);
                
                JSONObject jobj    = new JSONObject();

                //jobj.put("id",id);
                jobj.put("uname",uname);
                jobj.put("fname",fname);
                jobj.put("lname",lname);
                jobj.put("emailid",emailid);
                jobj.put("statename",statename);
                jobj.put("cityname",cityname);
                jobj.put("countryname",countryname);

                jArray.add(jobj);
                                               
        }
       
    
     JSONObject jObjDevice = new JSONObject();
        jObjDevice.put("device", jArray);
        JSONObject jObjDeviceList = new JSONObject();
        jObjDeviceList.put("devicelist", jObjDevice );
   
   
        pw.println(jObjDevice.toString());
          
       conn.close();
    //     pw.println("Disconnected from database");
    }     catch (Exception e)
    {
                e.printStackTrace();
        }
  }
}

I have just started with Extjs and surely goin to go for the MVC spring framwork but before that I have to do something convincing as a POC and demo it,to move forward.