1. #1
    Sencha User
    Join Date
    Nov 2011
    Posts
    149
    Answers
    2
    Vote Rating
    1
    sachintaware is on a distinguished road

      0  

    Default Answered: Validation using Java servlet

    Answered: Validation using Java servlet


    Hello
    I have a extjs login form and I am validating it against an xml schema.
    The validation process works fine standalone,but I want to redirect the user to a home page on successful login and error page on failure.

    My form is below:
    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.

    Please point if I am missing anything or point to relevant links which may be useful.

    Regards
    Sach

  2. The main problem I see is with your Servlet mappings in WEB-INF/web.xml. You're trying to lump all of your Servlets together into one <servlet> tag. Each Servet should be mapped separately, as shown below.

    Also, lowercase class file names violate Java naming conventions and the use of the 'default' package is discouraged. Consider refactoring the 'register' Servlet class file to com.yourDomain.yourApp.servlet.Register.

    Code:
    <servlet>
      <servlet-name>ValidationServlet</servlet-name>
      <servlet-class>com.extjs.ValidationServlet</servlet-class>
    </servlet>
    
     <servlet-mapping>
        <servlet-name>ValidationServlet</servlet-name>
        <url-pattern>/ValidationServlet</url-pattern>
     </servlet-mapping>
    
    <servlet>
      <servlet-name>register</servlet-name>
      <servlet-class>register</servlet-class>
    </servlet>        
    
     <servlet-mapping>
        <servlet-name>register</servlet-name>
        <url-pattern>/register</url-pattern>
     </servlet-mapping>

  3. #2
    Sencha User
    Join Date
    Nov 2011
    Posts
    149
    Answers
    2
    Vote Rating
    1
    sachintaware is on a distinguished road

      0  

    Default


    Hello
    Adding more specific details as i think above part was not clear.

    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
    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.

    Regrds
    Sach

  4. #3
    Sencha - Community Support Team friend's Avatar
    Join Date
    Apr 2011
    Posts
    895
    Answers
    106
    Vote Rating
    27
    friend has a spectacular aura about friend has a spectacular aura about

      0  

    Default


    The first problem I see is that you've set your Form panel to standardSubmit: true, yet you're trying to handle an Ajax-style result. A "standard" submit is the old-school, full-page redirect style of submitting, which appears to not be what you want. Remove standardSubmit: true from your Form panel configuration.

    Visit the Ext.form.Panel API documentation for a working, Ajax-style Form panel example.

    Your second problem is your Servlet. Allow me to first say that Servlets will kill you in the long-term; you seriously need to invest in the time and trouble of learning an MVC framework, where I suggest the Spring Web MVC framework.

    Having said that, your Servlet is not setting a content type prior to outputting your "JSON" string, so it's defaulting to text/html. That, and the full page submit you're doing, is why you only see your "JSON result" and not your grid page.

    Good luck!

  5. #4
    Sencha User
    Join Date
    Nov 2011
    Posts
    149
    Answers
    2
    Vote Rating
    1
    sachintaware is on a distinguished road

      0  

    Default Validation using Java servlet

    Validation using Java servlet


    Thank you friend.
    I was able to fix the first part.The callbacks are working now.But the json response still not.I tried changing the content type to ("application/json"), but did not work.
    Some more details i think i should add.
    This 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.

    Regards
    SachT

  6. #5
    Sencha - Community Support Team friend's Avatar
    Join Date
    Apr 2011
    Posts
    895
    Answers
    106
    Vote Rating
    27
    friend has a spectacular aura about friend has a spectacular aura about

      0  

    Default


    I have no idea why/how your second grid data Servlet is being called by the failure block of your login code. I'd have to see your complete login page, grid page and source for both Servlets. If possible, attach a .zip file containing these items and I'll be glad to take a look.

    Thanks.

  7. #6
    Sencha User tobiu's Avatar
    Join Date
    May 2007
    Location
    Munich (Germany)
    Posts
    2,684
    Answers
    130
    Vote Rating
    112
    tobiu is a name known to all tobiu is a name known to all tobiu is a name known to all tobiu is a name known to all tobiu is a name known to all tobiu is a name known to all

      0  

    Default


    this won't fix your issue, but you really should not write json strings manually.
    create objects and use a JSONencode function to create your string.

    Code:
    result="{success:true}";
    is no valid JSON since the property is not wrapped in quotes.
    Best regards
    Tobias Uhlig
    __________

    S-CIRCLES Social Network Engine

  8. #7
    Sencha User
    Join Date
    Nov 2011
    Posts
    149
    Answers
    2
    Vote Rating
    1
    sachintaware is on a distinguished road

      0  

    Default


    Hello Friend

    Attaching the source as suggested by you.
    Please go through and revert


    Thanks and Regards
    Sachin
    Attached Files

  9. #8
    Sencha User
    Join Date
    Nov 2011
    Posts
    149
    Answers
    2
    Vote Rating
    1
    sachintaware is on a distinguished road

      0  

    Default


    @tobiu

    Thanks for the inputs,will keep it in mind and make the changes.
    Actually read it in a post and implemented.

    Regards
    Sachin

  10. #9
    Sencha - Community Support Team friend's Avatar
    Join Date
    Apr 2011
    Posts
    895
    Answers
    106
    Vote Rating
    27
    friend has a spectacular aura about friend has a spectacular aura about

      0  

    Default


    The main problem I see is with your Servlet mappings in WEB-INF/web.xml. You're trying to lump all of your Servlets together into one <servlet> tag. Each Servet should be mapped separately, as shown below.

    Also, lowercase class file names violate Java naming conventions and the use of the 'default' package is discouraged. Consider refactoring the 'register' Servlet class file to com.yourDomain.yourApp.servlet.Register.

    Code:
    <servlet>
      <servlet-name>ValidationServlet</servlet-name>
      <servlet-class>com.extjs.ValidationServlet</servlet-class>
    </servlet>
    
     <servlet-mapping>
        <servlet-name>ValidationServlet</servlet-name>
        <url-pattern>/ValidationServlet</url-pattern>
     </servlet-mapping>
    
    <servlet>
      <servlet-name>register</servlet-name>
      <servlet-class>register</servlet-class>
    </servlet>        
    
     <servlet-mapping>
        <servlet-name>register</servlet-name>
        <url-pattern>/register</url-pattern>
     </servlet-mapping>

  11. #10
    Sencha User
    Join Date
    Nov 2011
    Posts
    149
    Answers
    2
    Vote Rating
    1
    sachintaware is on a distinguished road

      0  

    Default Validation using Java servlet

    Validation using Java servlet


    It worked!!!!!
    Thank you @Friend!!!!

    I thought so and hence added the file.I had learnt to write them that way.
    Also marked your comments and made the changes regarding files.

    A request though,you had pasted a link for the MVC Spring framework in previous comments.Could you please send me an example with CRUD operations using it or point to some useful links for the same??An easy one to start off understanding spring and its integration with extjs.

    It would be of great help.
    Keep up the good work.

    Regards
    Sachin

Thread Participants: 2

Tags for this Thread