Previously, I wrote a tutorial on integrating Spring Security and ExtJS login form. Now I am integrating the same Spring Security code with the Sencha Touch login form. Here I will cover the implementation of the form only and 2 use cases; login & logout. The sample code is based on Sencha Touch 1.1.0 and the foloder structure is following the Sencha Touch MVC.
First, lets see the login form and controller. The form has 2 fields, login id & password. When you click the login button, the form is submitted to http://<ownurl>/j_spring_security_check (the defLoginUrl in line 4 is defined in login.jsp).
Just a note, if you are using Sencha Touch 1.0 then you will need to implement a listener within the form to catch the “submit” and “exception” event. This is because there is a minor defect in the Ext.form.FormPanel submit function and it caused the form to ignore “success” & “failure” function in the submit.
test.views.LoginForm = Ext.extend(Ext.form.FormPanel, { scroll: 'vertical', fullscreen: true, url: defLoginUrl, items: [{ xtype: 'textfield', label: 'Login', name: 'j_username' },{ xtype: 'passwordfield', label: 'Password', name: 'j_password' }], dockedItems: [{ xtype: 'toolbar', dock: 'bottom', items: [{ text: 'Reset', handler: function() { test.views.loginForm.reset(); } },{ text: 'Login', ui: 'confirm', handler: function() { Ext.dispatch({ controller: test.controllers.loginController, action: 'submit', data: test.views.loginForm }); } }] }], initComponent: function() { test.views.LoginForm.superclass.initComponent.apply(this, arguments); } });
test.controllers.loginController = new Ext.Controller({ submit: function(options) { var theForm = options.data; test.views.loginForm.submit({ method: 'POST', waitMsg: { message: 'Processing', cls : 'demos-loading' }, scope: this, success: function(form, response) { window.location = '/'; }, failure: function(form, response) { Ext.Msg.alert('Warning', response.errorMessage); } }); } });
Depending on the result of the authentication the server side will return a JSON data. The format is
{"username":null,"errorMessage":"Login failed. Try again.","loggedIn":false,"success":false}
Once authenticated, you will see the main page with a logout button. The code is shown below.
test.views.Dashboard = Ext.extend(Ext.Panel, { fullscreen: true, dockedItems: [{ xtype: 'toolbar', title: 'Dashboard', dock: 'top', items: [{ xtype: 'button', text: 'Logout', ui: 'confirm', handler: function() { Ext.dispatch({ controller: test.controllers.dashboardController, action: 'logout' }); }, scope: this }] }], html: '<p>Welcome!</p>', initComponent: function() { test.views.Dashboard.superclass.initComponent.apply(this, arguments); } });
test.controllers.dashboardController = new Ext.Controller({ logout: function(options) { window.location = '/j_spring_security_logout'; } });
Hope that is useful. Happy coding!
References: