Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

MVC on the server and on the client

24,623 views

Published on

How to integrate SpringMVC and Backbone.js

Published in: Technology, Education
  • Be the first to comment

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 @sebarmeliJuly 10 , 2012 JAXConf, San Francisco
  2. Model - View - ControllerArchitectural Design Pattern ModelBusiness logic / presentation layer View ControllerReusabilityComponents isolation
  3. Passive and Active MVC View ModelPassive Approach ControllerActive Approach Controller View Observer pattern Model
  4. Java and MVCModel POJOView JSPController Servlet
  5. Spring MVCFront Controller pattern
  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. 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. 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. Why MVC in JavaScript ??AJAX application with lots of JS codeManaging efficiently jQuery selectors and callbacksDecoupling componentsSimplify communication with RESTful WS
  11. JavaScript and MVCModel JS objectView HTML TemplateController JS object
  12. JavaScript ‘MVC’ / ‘MV*’ LibraryDependencies: $(function(){ - Underscore.js // stuff here - json2.js Backbone.history.start(); }); - jQuery / ZeptoSingle Page Application (SPA)Connection to API over RESTful JSON interface
  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 & Validation var newContact = new MyApp.Contact(); newContact.set({‘firstname’ : ‘Lebron});
  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. 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. 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. 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. Model-View bindingvar view = Backbone.View.extend({ initialize: function(){ this.model.bind(“change”, this.render, this); }, render : function(){}});
  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. ‘My Contacts’ Application REST API URI HTTP Method /list GET /list POST /list/{contactId} PUT /list/{contactId} DELETE
  21. Questions?

×