由于Backbone中的请求是rest风格的,所以后台我选择的RestEasy来提供服务。
前端代码还是采用的我之前的一片文章http://webexpressor.iteye.com/blog/1608830
一、后台代码
主要目的是以json的格式返回一个BookList
1.我的项目是采用的maven来控制jar包的,pom文件为:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>test.backbone</groupId> <artifactId>backbone</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>2.3.0.GA</version> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jackson-provider</artifactId> <version>2.1.0.GA</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>tomcat-maven-plugin</artifactId> <version>1.1</version> <configuration> <!-- default 8080 --> <port>9090</port> <path>/</path> <uriEncoding>utf-8</uriEncoding> </configuration> </plugin> </plugins> </build> </project>
这时项目所以来的jar包就导入进来了,注意这里使用的是jackson provider来格式化json的,它返回的json中的格式为:[{"author":"zhangsan","isbn":"110123-456-789","title":"linux"},{"author":"lisi","isbn":"110123-456-789","title":"ejb"},{"author":"wangwu","isbn":"110123-456-789","title":"javascript"},{"author":"liudong","isbn":"110123-456-789","title":"java"},{"author":"liudong","isbn":"110123-456-789","title":"mysql"},{"author":"liudong","isbn":"110123-456-789","title":"resteasy"}]
这正是Backbone所需要的格式(Backbone好像不支持{"bookList":[{},{}]}这种格式)。
2.配置web.xml
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Restful Web Application</display-name> <context-param> <param-name>javax.ws.rs.Application</param-name> <param-value>com.backbone.service.MyApplication</param-value> </context-param> <listener> <listener-class> org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap </listener-class> </listener> <servlet> <servlet-name>resteasy-servlet</servlet-name> <servlet-class> org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher </servlet-class> </servlet> <servlet-mapping> <servlet-name>resteasy-servlet</servlet-name> <url-pattern>/app/*</url-pattern> </servlet-mapping> </web-app>
3.定义Book类
package com.backbone.model; public class Book { private String author; private String ISBN; private String title; public Book() { } public Book(String author, String ISBN, String title) { this.author = author; this.ISBN = ISBN; this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getISBN() { return ISBN; } public void setISBN(String ISBN) { this.ISBN = ISBN; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
4.编写bookService
package com.backbone.service; import java.util.ArrayList; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import com.backbone.model.Book; @Path("/app/book") public class BookService { @GET @Path("/get") @Produces("application/json") public List<Book> findBook(){ List<Book> books = new ArrayList<Book>(); books.add(new Book("zhangsan","110123-456-789","linux")); books.add(new Book("lisi","110123-456-789","ejb")); books.add(new Book("wangwu","110123-456-789","javascript")); books.add(new Book("liudong","110123-456-789","java")); books.add(new Book("liudong","110123-456-789","mysql")); books.add(new Book("liudong","110123-456-789","resteasy")); return books; } }
这里配置了访问的路径,及返回的格式
5.编写resteasy入口Application
package com.backbone.service; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; public class MyApplication extends Application{ private Set<Object> singletons = new HashSet<Object>(); private Set<Class<?>> empty = new HashSet<Class<?>>(); public MyApplication(){ singletons.add(new BookService()); } @Override public Set<Class<?>> getClasses() { return empty; } @Override public Set<Object> getSingletons() { return singletons; } }
到这一步服务器已经写好了,启动tomcat,在地址栏里输入http://localhost:9090/app/book/get 就可以看到服务器返回的结果了
二、客户端代码
1.app.js
$(document).ready(function(){ var Book = Backbone.Model.extend({}); var BookCollection = Backbone.Collection.extend({ model: Book }); var BookView = Backbone.View.extend({ tagName:'li', //_.template是Underscore中的方法 template:_.template($('#item-template').html()), // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { $(this.el).html(this.template(this.model.toJSON())); return this;//always return this }, events:{ "click":"viewDetail"//绑定单击事件 }, viewDetail:function(){ console.log(this.model.toJSON()); alert('你选择了'+this.model.get('title')); } }); var AppView = Backbone.View.extend({ el: $('#bookList'), initialize: function(){ var that = this; this.books = new BookCollection; this.books.fetch({ method:'get', url:'/app/book/get', success:function(data){ console.log(data); that.books.add(data.models); that.render(); } }); }, render: function(){ console.log(this.books.models); var that = this; _.each(this.books.models, function(item){ //动态传入model数据 var bookView = new BookView({model: item}); that.$el.append(bookView.render().el); },this); } }); var app = new AppView; });
2.index.html
<!doctype html> <html> <head> <meta charset="utf-8"/> </head> <body> <ul id="bookList"></ul> <script src="js/jquery-1.7.1.min.js"></script> <script src="js/underscore-min.js"></script> <script src="js/backbone.0.9.2.js"></script> <script src="js/app.js"></script> <script type="text/template" id="item-template"> author:<%=author %><br/> ISBN:<%= isbn %><br/> title:<%= title %><br/> </script> </body> </html>
整个项目就搭建好了,输入http://localhost:9090/index.html 可以进行测试
整个项目代码我放上来了,供参考。