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

Repository design pattern in laravel
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravel
Sameer Poudel
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 

What's hot (20)

[LetSwift 2023] 객체지향-함수형 아키텍처 직접 만들기
[LetSwift 2023] 객체지향-함수형 아키텍처 직접 만들기[LetSwift 2023] 객체지향-함수형 아키텍처 직접 만들기
[LetSwift 2023] 객체지향-함수형 아키텍처 직접 만들기
 
Struts Basics
Struts BasicsStruts Basics
Struts Basics
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
Angular
AngularAngular
Angular
 
AngularJS
AngularJSAngularJS
AngularJS
 
Tutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo FrameworkTutorial: Develop an App with the Odoo Framework
Tutorial: Develop an App with the Odoo Framework
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Master page in Asp.net
Master page in Asp.netMaster page in Asp.net
Master page in Asp.net
 
Styled Components & React.js
Styled Components & React.jsStyled Components & React.js
Styled Components & React.js
 
Developing New Widgets for your Views in Owl
Developing New Widgets for your Views in OwlDeveloping New Widgets for your Views in Owl
Developing New Widgets for your Views in Owl
 
Acrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVMAcrhitecture deisign pattern_MVC_MVP_MVVM
Acrhitecture deisign pattern_MVC_MVP_MVVM
 
Jsf presentation
Jsf presentationJsf presentation
Jsf presentation
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
The Integration of Laravel with Swoole
The Integration of Laravel with SwooleThe Integration of Laravel with Swoole
The Integration of Laravel with Swoole
 
The six key steps to AEM architecture
The six key steps to AEM architectureThe six key steps to AEM architecture
The six key steps to AEM architecture
 
Repository design pattern in laravel
Repository design pattern in laravelRepository design pattern in laravel
Repository design pattern in laravel
 
Maven 3 Overview
Maven 3  OverviewMaven 3  Overview
Maven 3 Overview
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 

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.1
Michał 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 JPA
Cheng 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.js
Carol McDonald
 
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
martinlippert
 
Modern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScriptModern Architectures with Spring and JavaScript
Modern Architectures with Spring and JavaScript
martinlippert
 
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
DienoSaurus
 
Bmd opdracht 6.1
Bmd opdracht 6.1Bmd opdracht 6.1
Bmd opdracht 6.1
DienoSaurus
 
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 change
Elaine 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

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
Soós Gábor
 

Similar to MVC on the server and on the client (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

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

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 

MVC on the server and on the client

  • 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