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

Introduction to JMS and Message-Driven POJOs
Introduction to JMS and Message-Driven POJOsIntroduction to JMS and Message-Driven POJOs
Introduction to JMS and Message-Driven POJOs
Matt Stine
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
Krazy Koder
 

What's hot (20)

Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Android Screen Containers & Layouts
Android Screen Containers & LayoutsAndroid Screen Containers & Layouts
Android Screen Containers & Layouts
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Introduction to JMS and Message-Driven POJOs
Introduction to JMS and Message-Driven POJOsIntroduction to JMS and Message-Driven POJOs
Introduction to JMS and Message-Driven POJOs
 
Demystifying Angular Animations
Demystifying Angular AnimationsDemystifying Angular Animations
Demystifying Angular Animations
 
Magento Indexes
Magento IndexesMagento Indexes
Magento Indexes
 
Connexion jdbc
Connexion jdbcConnexion jdbc
Connexion jdbc
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
React Nativeの光と闇
React Nativeの光と闇React Nativeの光と闇
React Nativeの光と闇
 
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
 
Emmet cheat-sheet
Emmet cheat-sheetEmmet cheat-sheet
Emmet cheat-sheet
 
Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0
 
UDA-Componentes RUP. Formulario
UDA-Componentes RUP. FormularioUDA-Componentes RUP. Formulario
UDA-Componentes RUP. Formulario
 
Android ui dialog
Android ui dialogAndroid ui dialog
Android ui dialog
 
An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST An Overview of Web Services: SOAP and REST
An Overview of Web Services: SOAP and REST
 
Angular 9
Angular 9 Angular 9
Angular 9
 
React & Redux
React & ReduxReact & Redux
React & Redux
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVC
 
React / Redux Architectures
React / Redux ArchitecturesReact / Redux Architectures
React / Redux Architectures
 

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

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
FIDO Alliance
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
FIDO Alliance
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
panagenda
 

Recently uploaded (20)

Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024Long journey of Ruby Standard library at RubyKaigi 2024
Long journey of Ruby Standard library at RubyKaigi 2024
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 

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