Monday, October 8, 2012

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.

0 comments:

Post a Comment