SlideShare a Scribd company logo
1 of 22
MVC on the server and
     on the client
 How to integrate Spring MVC and
           Backbone.js



             Sebastiano Armeli-Battana
                    @sebarmeli

July 10 , 2012                       JAXConf, San Francisco
Model - View - Controller

Architectural Design Pattern
                                             Model


Business logic / presentation layer

                                      View           Controller
Reusability


Components isolation
Passive and Active MVC
                         View                Model

Passive Approach


                                Controller




Active Approach        Controller            View


                                              Observer
                                               pattern

                                    Model
Java and MVC

Model                       POJO


View                         JSP


Controller                  Servlet
Spring MVC
Front Controller pattern
Getting started
web.xml
  <servlet>
     <servlet-name>dispatcher</servlet-name>
     <servlet-class>
org.springframework.web.servlet.DispatcherServlet
     </servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
Spring MVC 3 configurations
dispatcher-servlet.xml
<context:component-scan base-package=”com.example”

<mvc:annotation-driven />

<mvc:view-controller path=”/page1” view-name=”view1” />

<mvc:resources mapping=”/resources/**” location=”/resources” />


<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name=”mediaTypes”>
         ...
    </property>
    <property name=”viewResolvers”>
         ...
    </property>
</bean>
Spring MVC in action
  C   @Controller
  O   public class ContactsController {
  N       @Autowired
  T       private ContactService service;
  R
  O       @RequestMapping(value=”/list”, method = RequestMethod.GET)
  L       public @ResponseBody List<Contact> getContacts() {
  L           return service.getContacts();
  E       }
  R   }




Service Layer (@Service)
                                                     VIEW
   DAO (@Repository)                  [{
                                           “id” : 31,
                                           “firstname” : “LeBron”,
                                           “lastname” : “James”,

      MODEL
                                           “telephone” : “111-222-3333”
                                      }]
What about the Model?
         @Entity
         @Table(name=”Contacts”)
         public class Contact {

              @Id
              @Column(name = ”ID”)
              @GeneratedValue
              private Integer id;

              @Column(name = “FIRSTNAME”)
              private String firstname;

              public String getFirstname(){
                return firstname;
              }

              public void setFirstname(){
                this.firstname = firstname;
              }

             ...
         }
Why MVC in JavaScript ??

AJAX application with lots of JS code


Managing efficiently jQuery selectors and callbacks


Decoupling components


Simplify communication with RESTful WS
JavaScript and MVC

Model                    JS object


View                   HTML Template


Controller               JS object
JavaScript ‘MVC’ / ‘MV*’ Library


Dependencies:                      $(function(){
	

 - Underscore.js                  // stuff here
    - json2.js                       Backbone.history.start();
                                   });
	

 - jQuery / Zepto


Single Page Application (SPA)


Connection to API over RESTful JSON interface
Model
Represents data (JSON)       {
                                 “id” : 31,
                                 “firstname” : “LeBron”,
                                 “lastname” : “James”,
                                 “telephone” : “111-222-3333”
                             }



Key-value attributes         MyApp.Contact = Backbone.Model.extend({

                                 defaults: {
                                    firstname : “”,
                                    lastname : “”,
                                    telephone : “”
                                 },
Domain-specific methods           getFullName: function() {
                                    return this.fullname + this.lastname;
                                 },

                                 validate: function(){}

                             });
Custom events & Validation   var newContact = new MyApp.Contact();
                             newContact.set({‘firstname’ : ‘Lebron'});
Collection
Set of models              MyApp.Contacts = Backbone.Collection.extend({

                             model: MyAppp.Contact,

                             url: ‘/list’

                           });

url / url()                var collection = new MyApp.Contacts(),
                             model1 = new MyApp.Contact();

                           collection.add(model1);




create() / add() / remove()/ reset()



get() / getByCid()
Router

Routing client-side “states”
                         MyApp.AppRouter = Backbone.Router.extend({

                           routes: {
                              “” : “index”,
                              “list-contacts” : “listContacts”
“routes” map               },

                           index : function() {
                             // stuff here
                           }

                           listContacts : function() {
                             // stuff here
List of actions            }
                         });

                         var router = new MyApp.AppRouter();
View

Logical view     MyApp.ListContactsView = Backbone.View.extend({

                   className: ‘list’,

                   initialize: function(){
                      // stuff here

‘el’ attribute     },

                   events: {
                     “click a”: “goToLink”
                   }


Event handlers     goToLink : function() {}

                   render : function(){
                     this.$el.html(“<p>Something</p>”);
                   }
                 });

render()         var view = new MyApp.ListContactsView();
                 view.render();
View + HTML Template

  Pick one client-side templating engine!
  (E.g. Handlebars.js, Haml-js, ICanHaz.js)


  Isolate HTML into Template
View                                                   ICanHaz.js
MyApp.ContactsView = Backbone.View.extend({

  ...
                                               HTML template
  render : function(){
                                               <script type=”text/html”
      var obj = this.model.toJSON(),           id=”contactTemplate”>
        template = ich.contactTemplate(obj);     <p>First name : {{firstname}}</p>
                                                 <p>Last name : {{lastname}}</p>
      this.$el.html(template);                   <p>Telephone : {{telephone}}</p>
  }                                            script>
});

var view = new MyApp.ContactsView();
view.render();
Model-View binding

var view = Backbone.View.extend({

 initialize: function(){

  this.model.bind(“change”, this.render, this);

 },

 render : function(){}

});
Backbone.js and REST
Backbone.sync(): CRUD => HTTP Methods
POST
      collection.create(model) / model.save()
GET
         collection.fetch() / model.fetch()
PUT
                    model.save()
DELETE

                  model.destroy()


(jQuery/Zepto).ajax()
‘My Contacts’ Application

                      REST API

                  URI           HTTP Method

                  /list            GET
                  /list           POST
            /list/{contactId}      PUT
            /list/{contactId}    DELETE
Questions?

More Related Content

What's hot

ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentationivpol
 
Angular 6 Form Validation with Material
Angular 6 Form Validation with MaterialAngular 6 Form Validation with Material
Angular 6 Form Validation with MaterialMalika Munaweera
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Rafael Wilber Kerr
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentationBhavin Shah
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkShravan A
 
Empower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsEmpower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsOdoo
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mappingAbhilash M A
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
MVC, MVP e MVVM: Uma Comparação de Padrões Arquiteturais
MVC, MVP e MVVM: Uma Comparação de Padrões ArquiteturaisMVC, MVP e MVVM: Uma Comparação de Padrões Arquiteturais
MVC, MVP e MVVM: Uma Comparação de Padrões ArquiteturaisJorge Tressino Rua
 

What's hot (20)

ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Angular 6 Form Validation with Material
Angular 6 Form Validation with MaterialAngular 6 Form Validation with Material
Angular 6 Form Validation with Material
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 
Asp net
Asp netAsp net
Asp net
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)Graphql Intro (Tutorial and Example)
Graphql Intro (Tutorial and Example)
 
Quiery builder
Quiery builderQuiery builder
Quiery builder
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity Framework
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Empower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsEmpower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo Mixins
 
ORM: Object-relational mapping
ORM: Object-relational mappingORM: Object-relational mapping
ORM: Object-relational mapping
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Angular
AngularAngular
Angular
 
Odata
OdataOdata
Odata
 
Web api
Web apiWeb api
Web api
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
MVC, MVP e MVVM: Uma Comparação de Padrões Arquiteturais
MVC, MVP e MVVM: Uma Comparação de Padrões ArquiteturaisMVC, MVP e MVVM: Uma Comparação de Padrões Arquiteturais
MVC, MVP e MVVM: Uma Comparação de Padrões Arquiteturais
 

Viewers also liked

Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPACheng Ta Yeh
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"
RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"
RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"Jānis Grabis
 
JAX 2012: Moderne Architektur mit Spring und JavaScript
JAX 2012: Moderne Architektur mit Spring und JavaScriptJAX 2012: Moderne Architektur mit Spring und JavaScript
JAX 2012: Moderne Architektur mit Spring und JavaScriptmartinlippert
 
Modern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScriptModern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScriptmartinlippert
 
Creating MVC Application with backbone js
Creating MVC Application with backbone jsCreating MVC Application with backbone js
Creating MVC Application with backbone jsMindfire Solutions
 
Software Architecture Patterns
Software Architecture PatternsSoftware Architecture Patterns
Software Architecture PatternsAssaf Gannon
 
Vacademia 13 3 нн 2015
Vacademia 13 3 нн 2015Vacademia 13 3 нн 2015
Vacademia 13 3 нн 2015Mikhail Morozov
 
Build my dream 4 opdracht 02 deel 1/2
Build my dream 4 opdracht 02  deel 1/2Build my dream 4 opdracht 02  deel 1/2
Build my dream 4 opdracht 02 deel 1/2DienoSaurus
 
Bmd opdracht 6.1
Bmd opdracht 6.1Bmd opdracht 6.1
Bmd opdracht 6.1DienoSaurus
 
Tutorial: How to work with app “3D Molecules Edit & Test”
Tutorial: How to work with app “3D Molecules Edit & Test” Tutorial: How to work with app “3D Molecules Edit & Test”
Tutorial: How to work with app “3D Molecules Edit & Test” Mikhail Morozov
 
Climate change
Climate changeClimate change
Climate changeElaine Yu
 

Viewers also liked (20)

Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPAIntegrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
Integrate Spring MVC with RequireJS & Backbone.js & Spring Data JPA
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"
RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"
RTU maģistra profesionālo studiju programma "Informācijas tehnoloģija"
 
JAX 2012: Moderne Architektur mit Spring und JavaScript
JAX 2012: Moderne Architektur mit Spring und JavaScriptJAX 2012: Moderne Architektur mit Spring und JavaScript
JAX 2012: Moderne Architektur mit Spring und JavaScript
 
Modern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScriptModern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScript
 
Creating MVC Application with backbone js
Creating MVC Application with backbone jsCreating MVC Application with backbone js
Creating MVC Application with backbone js
 
Software Architecture Patterns
Software Architecture PatternsSoftware Architecture Patterns
Software Architecture Patterns
 
Vacademia 13 3 нн 2015
Vacademia 13 3 нн 2015Vacademia 13 3 нн 2015
Vacademia 13 3 нн 2015
 
Build my dream 4 opdracht 02 deel 1/2
Build my dream 4 opdracht 02  deel 1/2Build my dream 4 opdracht 02  deel 1/2
Build my dream 4 opdracht 02 deel 1/2
 
Bmd opdracht 1
Bmd opdracht 1Bmd opdracht 1
Bmd opdracht 1
 
Thanksgiving role play-hollaus
Thanksgiving role play-hollausThanksgiving role play-hollaus
Thanksgiving role play-hollaus
 
Summit 17 04
Summit 17 04Summit 17 04
Summit 17 04
 
Bmd opdracht 6.1
Bmd opdracht 6.1Bmd opdracht 6.1
Bmd opdracht 6.1
 
Bmd 6 o1 show
Bmd 6 o1 showBmd 6 o1 show
Bmd 6 o1 show
 
Burns night
Burns nightBurns night
Burns night
 
Violència bullying
Violència    bullyingViolència    bullying
Violència bullying
 
Scotland
ScotlandScotland
Scotland
 
Tutorial: How to work with app “3D Molecules Edit & Test”
Tutorial: How to work with app “3D Molecules Edit & Test” Tutorial: How to work with app “3D Molecules Edit & Test”
Tutorial: How to work with app “3D Molecules Edit & Test”
 
Climate change
Climate changeClimate change
Climate change
 

Similar to MVC on the server and on the client: Integrating Spring MVC and Backbone.js

MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...jaxconf
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAERon Reiter
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
 
Emberjs as a rails_developer
Emberjs as a rails_developer Emberjs as a rails_developer
Emberjs as a rails_developer Sameera Gayan
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09Daniel Bryant
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgetsBehnam Taraghi
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto UniversitySC5.io
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 
Spring MVC introduction HVA
Spring MVC introduction HVASpring MVC introduction HVA
Spring MVC introduction HVAPeter Maas
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoHasnain Iqbal
 

Similar to MVC on the server and on the client: Integrating Spring MVC and Backbone.js (20)

MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAEWriting HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Emberjs as a rails_developer
Emberjs as a rails_developer Emberjs as a rails_developer
Emberjs as a rails_developer
 
Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)
 
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09L2 Web App Development Guest Lecture At University of Surrey 20/11/09
L2 Web App Development Guest Lecture At University of Surrey 20/11/09
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
MVC pattern for widgets
MVC pattern for widgetsMVC pattern for widgets
MVC pattern for widgets
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Java beans
Java beansJava beans
Java beans
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Spring MVC introduction HVA
Spring MVC introduction HVASpring MVC introduction HVA
Spring MVC introduction HVA
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael PizzoADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
 
Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 

More from Sebastiano Armeli

Managing a software engineering team
Managing a software engineering teamManaging a software engineering team
Managing a software engineering teamSebastiano Armeli
 
Enforcing coding standards in a JS project
Enforcing coding standards in a JS projectEnforcing coding standards in a JS project
Enforcing coding standards in a JS projectSebastiano Armeli
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
Dependency management & Package management in JavaScript
Dependency management & Package management in JavaScriptDependency management & Package management in JavaScript
Dependency management & Package management in JavaScriptSebastiano Armeli
 
Backbone.js in a real-life application
Backbone.js in a real-life applicationBackbone.js in a real-life application
Backbone.js in a real-life applicationSebastiano Armeli
 
Getting started with Selenium 2
Getting started with Selenium 2Getting started with Selenium 2
Getting started with Selenium 2Sebastiano Armeli
 

More from Sebastiano Armeli (12)

Managing a software engineering team
Managing a software engineering teamManaging a software engineering team
Managing a software engineering team
 
Enforcing coding standards in a JS project
Enforcing coding standards in a JS projectEnforcing coding standards in a JS project
Enforcing coding standards in a JS project
 
Enforcing coding standards
Enforcing coding standardsEnforcing coding standards
Enforcing coding standards
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Dependency management & Package management in JavaScript
Dependency management & Package management in JavaScriptDependency management & Package management in JavaScript
Dependency management & Package management in JavaScript
 
Karma - JS Test Runner
Karma - JS Test RunnerKarma - JS Test Runner
Karma - JS Test Runner
 
RequireJS
RequireJSRequireJS
RequireJS
 
Lazy load Everything!
Lazy load Everything!Lazy load Everything!
Lazy load Everything!
 
Backbone.js in a real-life application
Backbone.js in a real-life applicationBackbone.js in a real-life application
Backbone.js in a real-life application
 
Getting started with Selenium 2
Getting started with Selenium 2Getting started with Selenium 2
Getting started with Selenium 2
 
Web Storage
Web StorageWeb Storage
Web Storage
 

Recently uploaded

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 

Recently uploaded (20)

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 

MVC on the server and on the client: Integrating Spring MVC and Backbone.js

  • 1. MVC on the server and on the client How to integrate Spring MVC and Backbone.js Sebastiano Armeli-Battana @sebarmeli July 10 , 2012 JAXConf, San Francisco
  • 2. Model - View - Controller Architectural Design Pattern Model Business logic / presentation layer View Controller Reusability Components isolation
  • 3. Passive and Active MVC View Model Passive Approach Controller Active Approach Controller View Observer pattern Model
  • 4. Java and MVC Model POJO View JSP Controller Servlet
  • 6. Getting started web.xml <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
  • 7. Spring MVC 3 configurations dispatcher-servlet.xml <context:component-scan base-package=”com.example” <mvc:annotation-driven /> <mvc:view-controller path=”/page1” view-name=”view1” /> <mvc:resources mapping=”/resources/**” location=”/resources” /> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name=”mediaTypes”> ... </property> <property name=”viewResolvers”> ... </property> </bean>
  • 8. Spring MVC in action C @Controller O public class ContactsController { N @Autowired T private ContactService service; R O @RequestMapping(value=”/list”, method = RequestMethod.GET) L public @ResponseBody List<Contact> getContacts() { L return service.getContacts(); E } R } Service Layer (@Service) VIEW DAO (@Repository) [{ “id” : 31, “firstname” : “LeBron”, “lastname” : “James”, MODEL “telephone” : “111-222-3333” }]
  • 9. What about the Model? @Entity @Table(name=”Contacts”) public class Contact { @Id @Column(name = ”ID”) @GeneratedValue private Integer id; @Column(name = “FIRSTNAME”) private String firstname; public String getFirstname(){ return firstname; } public void setFirstname(){ this.firstname = firstname; } ... }
  • 10.
  • 11. Why MVC in JavaScript ?? AJAX application with lots of JS code Managing efficiently jQuery selectors and callbacks Decoupling components Simplify communication with RESTful WS
  • 12. JavaScript and MVC Model JS object View HTML Template Controller JS object
  • 13. JavaScript ‘MVC’ / ‘MV*’ Library Dependencies: $(function(){ - Underscore.js // stuff here - json2.js Backbone.history.start(); }); - jQuery / Zepto Single Page Application (SPA) Connection to API over RESTful JSON interface
  • 14. Model Represents data (JSON) { “id” : 31, “firstname” : “LeBron”, “lastname” : “James”, “telephone” : “111-222-3333” } Key-value attributes MyApp.Contact = Backbone.Model.extend({ defaults: { firstname : “”, lastname : “”, telephone : “” }, Domain-specific methods getFullName: function() { return this.fullname + this.lastname; }, validate: function(){} }); Custom events & Validation var newContact = new MyApp.Contact(); newContact.set({‘firstname’ : ‘Lebron'});
  • 15. Collection Set of models MyApp.Contacts = Backbone.Collection.extend({ model: MyAppp.Contact, url: ‘/list’ }); url / url() var collection = new MyApp.Contacts(), model1 = new MyApp.Contact(); collection.add(model1); create() / add() / remove()/ reset() get() / getByCid()
  • 16. Router Routing client-side “states” MyApp.AppRouter = Backbone.Router.extend({ routes: { “” : “index”, “list-contacts” : “listContacts” “routes” map }, index : function() { // stuff here } listContacts : function() { // stuff here List of actions } }); var router = new MyApp.AppRouter();
  • 17. View Logical view MyApp.ListContactsView = Backbone.View.extend({ className: ‘list’, initialize: function(){ // stuff here ‘el’ attribute }, events: { “click a”: “goToLink” } Event handlers goToLink : function() {} render : function(){ this.$el.html(“<p>Something</p>”); } }); render() var view = new MyApp.ListContactsView(); view.render();
  • 18. View + HTML Template Pick one client-side templating engine! (E.g. Handlebars.js, Haml-js, ICanHaz.js) Isolate HTML into Template View ICanHaz.js MyApp.ContactsView = Backbone.View.extend({ ... HTML template render : function(){ <script type=”text/html” var obj = this.model.toJSON(), id=”contactTemplate”> template = ich.contactTemplate(obj); <p>First name : {{firstname}}</p> <p>Last name : {{lastname}}</p> this.$el.html(template); <p>Telephone : {{telephone}}</p> } script> }); var view = new MyApp.ContactsView(); view.render();
  • 19. Model-View binding var view = Backbone.View.extend({ initialize: function(){ this.model.bind(“change”, this.render, this); }, render : function(){} });
  • 20. Backbone.js and REST Backbone.sync(): CRUD => HTTP Methods POST collection.create(model) / model.save() GET collection.fetch() / model.fetch() PUT model.save() DELETE model.destroy() (jQuery/Zepto).ajax()
  • 21. ‘My Contacts’ Application REST API URI HTTP Method /list GET /list POST /list/{contactId} PUT /list/{contactId} DELETE

Editor's Notes

  1. \n
  2. \n\n\n\n\n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n\npring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverterbuilt on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.\n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n\n
  23. \n\n
  24. \n\n