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

1,413 views

Published on

MVC is a well-known pattern used to reduce complexity and to increase reusability of your code, widely adopted in server-side languages. Spring MVC is an example of a really powerful framework that adopts this pattern extensively allowing you to create easily RESTful web services. MVC can also be applied to the client now and this approach really suits AJAX applications and single page applications. Backbone.js is one of the frameworks available to enforce this pattern. In this session we will explore how well you can integrate Spring MVC and Backbone.js in a really performant and neat single page application. Focus will be put on how Backbone.js can consume RESTful web services.

Published in: Technology, Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,413
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
57
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

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

  1. 1. MVC on the server and on the client How to integrate Spring MVC and Backbone.js Sebastiano Armeli-Battana @sebarmeliJuly 10 , 2012 JAXConf, San Francisco
  2. 2. Model - View - ControllerArchitectural Design Pattern ModelBusiness logic / presentation layer View ControllerReusabilityComponents isolation
  3. 3. Passive and Active MVC View ModelPassive Approach Controller Controller ViewActive Approach Observer pattern Model
  4. 4. Java and MVCModel POJOView JSPController Servlet
  5. 5. Spring MVCFront Controller pattern
  6. 6. Getting startedweb.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. 7. Spring MVC 3 configurationsdispatcher-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” /><beanclass="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name=”mediaTypes”> ... </property> <property name=”viewResolvers”> ... </property></bean>
  8. 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. 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. 10. Why MVC in JavaScript ??AJAX application with lots of JS codeManaging efficiently jQuery selectors and callbacksDecoupling componentsSimplify communication with RESTful WS
  11. 11. JavaScript and MVCModel JS objectView HTML TemplateController JS object
  12. 12. JavaScript ‘MVC’ / ‘MV*’ LibraryDependencies: - Underscore.js $(function(){ - json2.js // stuff here Backbone.history.start(); - jQuery / Zepto });Single Page Application (SPA)Connection to API over RESTful JSON interface
  13. 13. ModelRepresents 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});
  14. 14. CollectionSet 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()
  15. 15. RouterRouting client-side “states” MyApp.AppRouter = Backbone.Router.extend({ routes: { “” : “index”, “list-contacts” : “listContacts”“routes” map }, index : function() { // stuff here } listContacts : function() { // stuff hereList of actions } }); var router = new MyApp.AppRouter();
  16. 16. ViewLogical 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();
  17. 17. View + HTML Template Pick one client-side templating engine! (E.g. Handlebars.js, Haml-js, ICanHaz.js) Isolate HTML into TemplateView ICanHaz.jsMyApp.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();
  18. 18. Model-View bindingvar view = Backbone.View.extend({initialize: function(){this.model.bind(“change”, this.render, this);},render : function(){}});
  19. 19. Backbone.js and RESTBackbone.sync(): CRUD => HTTP MethodsPOST collection.create(model) / model.save()GET collection.fetch() / model.fetch()PUT model.save()DELETE model.destroy()(jQuery/Zepto).ajax()
  20. 20. ‘My Contacts’ Application REST API URI HTTP Method /list GET /list POST /list/{contactId} PUT /list/{contactId} DELETE
  21. 21. Questions?

×