SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
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




                      Controller            View

Active Approach
                                            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
     @Controller
     public class ContactsController {

         @Autowired
         private ContactService service;
  CONTROLLER
       @RequestMapping(value=”/list”, method = RequestMethod.GET)
         public @ResponseBody List<Contact> getContacts() {

             return service.getContacts();
         }
     }




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:
     - Underscore.js               $(function(){

 - json2.js                         // stuff here
                                    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 &           var newContact = new MyApp.Contact();
Validation                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?

Mais conteúdo relacionado

Mais procurados

Injection de dépendances dans Symfony >= 3.3
Injection de dépendances dans Symfony >= 3.3Injection de dépendances dans Symfony >= 3.3
Injection de dépendances dans Symfony >= 3.3Vladyslav Riabchenko
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQueryPhDBrown
 
Modules and injector
Modules and injectorModules and injector
Modules and injectorEyal Vardi
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databindingBoulos Dib
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법Jeado Ko
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and BeautifulBefore there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and Beautifulchicagonewsonlineradio
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScripttaobao.com
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + SpringBryan Hsueh
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsIMC Institute
 

Mais procurados (19)

Data binding w Androidzie
Data binding w AndroidzieData binding w Androidzie
Data binding w Androidzie
 
Injection de dépendances dans Symfony >= 3.3
Injection de dépendances dans Symfony >= 3.3Injection de dépendances dans Symfony >= 3.3
Injection de dépendances dans Symfony >= 3.3
 
Speaking Eloquent Eloquently
Speaking Eloquent EloquentlySpeaking Eloquent Eloquently
Speaking Eloquent Eloquently
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Metaworks3
Metaworks3Metaworks3
Metaworks3
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQuery
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Knockoutjs databinding
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and BeautifulBefore there was Hoop Dreams, there was McDonald's: Strange and Beautiful
Before there was Hoop Dreams, there was McDonald's: Strange and Beautiful
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript運用Closure Compiler 打造高品質的JavaScript
運用Closure Compiler 打造高品質的JavaScript
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Jsf
JsfJsf
Jsf
 
Web 6 | JavaScript DOM
Web 6 | JavaScript DOMWeb 6 | JavaScript DOM
Web 6 | JavaScript DOM
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 

Destaque

The Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun SmithThe Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun Smithjaxconf
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargentajaxconf
 
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...jaxconf
 
JSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian HlavatsJSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian Hlavatsjaxconf
 
From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEjaxconf
 
Understanding Java Garbage Collection and What You Can Do About It: Gil Tene
Understanding Java Garbage Collection and What You Can Do About It: Gil TeneUnderstanding Java Garbage Collection and What You Can Do About It: Gil Tene
Understanding Java Garbage Collection and What You Can Do About It: Gil Tenejaxconf
 
Future of the Web - Yehuda Katz
Future of the Web - Yehuda KatzFuture of the Web - Yehuda Katz
Future of the Web - Yehuda Katzjaxconf
 
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin HerbasThe New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbasjaxconf
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long jaxconf
 
The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Longjaxconf
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remanijaxconf
 
Building an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen TingBuilding an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen Tingjaxconf
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta jaxconf
 
What you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie AllenWhat you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie Allenjaxconf
 
Java PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao KandJava PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao Kandjaxconf
 
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu BariApache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu Barijaxconf
 

Destaque (16)

The Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun SmithThe Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun Smith
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
 
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
 
JSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian HlavatsJSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian Hlavats
 
From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEE
 
Understanding Java Garbage Collection and What You Can Do About It: Gil Tene
Understanding Java Garbage Collection and What You Can Do About It: Gil TeneUnderstanding Java Garbage Collection and What You Can Do About It: Gil Tene
Understanding Java Garbage Collection and What You Can Do About It: Gil Tene
 
Future of the Web - Yehuda Katz
Future of the Web - Yehuda KatzFuture of the Web - Yehuda Katz
Future of the Web - Yehuda Katz
 
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin HerbasThe New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Long
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remani
 
Building an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen TingBuilding an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen Ting
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
 
What you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie AllenWhat you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie Allen
 
Java PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao KandJava PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao Kand
 
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu BariApache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
 

Semelhante a MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone.js: Sebastiano Armeli-Battana

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
 
Emberjs as a rails_developer
Emberjs as a rails_developer Emberjs as a rails_developer
Emberjs as a rails_developer Sameera Gayan
 
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
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
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
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2pyjonromero
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto UniversitySC5.io
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverSpike Brehm
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Codemotion
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 

Semelhante a MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone.js: Sebastiano Armeli-Battana (20)

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
 
Emberjs as a rails_developer
Emberjs as a rails_developer Emberjs as a rails_developer
Emberjs as a rails_developer
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
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
 
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)
 
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
 
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
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Backbone js
Backbone jsBackbone js
Backbone js
 
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++
 
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
Going fullstack React(ive) - Paulo Lopes - Codemotion Amsterdam 2017
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 

Último

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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 WorkerThousandEyes
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone.js: Sebastiano Armeli-Battana

  • 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 Controller View Active Approach 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 @Controller public class ContactsController { @Autowired private ContactService service; CONTROLLER @RequestMapping(value=”/list”, method = RequestMethod.GET) public @ResponseBody List<Contact> getContacts() { return service.getContacts(); } } 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: - Underscore.js $(function(){ - json2.js // stuff here 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 & var newContact = new MyApp.Contact(); Validation 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