eagleshi 发表于 2015-7-8 05:51:17

[译] 第二十二天: 用Spring, MongoDB和AngularJS开发单页应用

前言
  今天的30天挑战,我决定用Spring框架, MongoDB和AngularJS开发一个单页网页应用。我对Spring和MongoDB很熟悉但是没有AngualrJS和Spring框架一起用过。所以本文就来开发一个网摘程序就像几天前用EmberJS写的一样。在这个系列的第二天我们已经讨论过AngularJS基础知识,详情参考博客。本文我们来讨论最新版本的Spring框架如3.2.5 RELEASE, 不采用XML(甚至没有web.xml). 我们用Spring注释支持来配置所有东西,Spring MVC(同Spring框架一起)用来创建RESTful后端。AngularJS用做客户端MVC框架来开发前端。

程序用例
  本文我们开发个网摘程序允许用户发布和分享链接。OpenShift上有在线程序,程序有以下功能。


[*]当用户到程序'/' url, 可以看到保存在程序数据库中的一系列文章列表,后台,AngularJS调用了REST(/api/v1/stories)来获取所有文章。

[*]当用户点击任意文章,如 http://getbookmarks-shekhargulati.rhcloud.com/#/stories/528b9a8ce4b0da0473622359, 他可以看到文章的内容如谁提交的,什么时候提交的,还有文章摘要. AngularJS发出RESTful GET请求(/api/v1/stories/528b9a8ce4b0da0473622359) 来获得完整文章。

[*]最后,用户可以从http://getbookmarks-shekhargulati.rhcloud.com/#/stories/new 提交新文章,这回向RESTful后端发出POST请求,然后保存文章到MongoDB中,用户只需输入文章的url链接,程序会用之前开发的Goose Ectractor      RESTful去获取文章标题,主要图片和摘要。


前提准备


[*]Java基础知识,安装最新的Java Development      Kit(JDK), 可以安装OpenJDK 7或者Oracle JDK 7, OpenShift支持OpenJDK 6 和7.
[*]Spring基础知识。
[*]在OpenShift上注册。OpenShift完全免费,红帽给每个用户免费提供了3个Gears来运行程序。目前,这个资源分配合计有每人1.5GB内存,3GB磁盘空间。
[*]在本机安装rhc 客户端工具,rhc是ruby gem包,所以你需要安装1.8.7或以上版本的ruby。安装rhc,输入 sudo      gem install rhc. 如果已经安装了,确保是最新的,要更新rhc,输入sudo gem update rhc. 想了解rhc command-line 工具,更多帮助参考 https://www.openshift.com/developers/rhc-client-tools-install.
[*]用rhc setup 命令安装OpenShift. 执行命令可以帮你创建空间,上传ssh 密钥到OpenShift服务器。

Github仓库
  今天的demo放在github: day22-spring-angularjs-demo-app.

第一步:创建Tomcat 7程序
  用Tomcat 7和MongoDB cartridge新建程序开始。





$ rhc create-app getbookmarks tomcat-7 mongodb-2
View Code   这会创建一个叫gear的程序容器,安装所需的SELinux策略和cgroup配置,OpenShift也会为你安装一个私有git仓库,克隆到本地,然后它会把DNS传播到网络。可访问 http://getbookmarks-{domain-name}.rhcloud.com/ 查看程序。替换你自己唯一的OpenShift域名(有时也叫命名空间)。

第二步:删除模板代码
  接下来删除OpenShift创建的模板代码。





$ cd getbookmarks
$ git rm -rf src/main/webapp/*.jsp src/main/webapp/index.html src/main/webapp/images src/main/webapp/WEB-INF/web.xml
$ git commit -am "deleted template files"
View Code   注意,那也会删除web.xml.

第三步:更新po.xml
  接下来,用以下代码更新程序的pom.xml.






4.0.0
getbookmarks
getbookmarks
war
1.0
getbookmarks

UTF-8
1.7
1.7



org.springframework
spring-webmvc
3.2.5.RELEASE


org.springframework
spring-tx
3.2.5.RELEASE


org.springframework.data
spring-data-mongodb
1.3.2.RELEASE



org.codehaus.jackson
jackson-mapper-asl
1.9.13



javax.servlet
javax.servlet-api
3.1.0
provided






openshift

getbookmarks


maven-war-plugin
2.4

false
webapps
ROOT








View Code   以上pom.xml:


[*]添加Maven依赖给Spring-webmvc, spring-mongodb,      jackson, 和最新 servlet api.
[*]更新项目JDK 6到JDK 7.
[*]更新项目用最新Maven war插件,添加一个配置避免没有web.xml时build出错。
  更新好后,确保更新maven项目 右击> Maven > Update Project.

第四步:编写WebMvcConfig和AppConfig类
  新建包 com.getbookmarks.config 和类WebMvcConfig. 用以下代码替换,这个类会激活Spring Web MVC框架。





import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;
@EnableWebMvc
@ComponentScan(basePackageClasses = StoryResource.class)
@Configuration
public class WebMvcConfig{
}
View Code   接下来写另一个配置类AppConfig, Spring MongoDB对你在哪里实现接口有存储概念,Spring会因此生成一个proxy类,这使得写存储类很容易,移除了大量的样板式代码。Spring MongoDB允许我们通过指定@EnableMongoRepositories注释来声明激活Mongo存储。





import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.getbookmarks.repository.StoryRepository;
import com.mongodb.Mongo;

@Configuration
@EnableMongoRepositories(basePackageClasses = StoryRepository.class)
public class ApplicationConfig {

@Bean
public MongoTemplate mongoTemplate() throws Exception {
String openshiftMongoDbHost = System.getenv("OPENSHIFT_MONGODB_DB_HOST");
int openshiftMongoDbPort = Integer.parseInt(System.getenv("OPENSHIFT_MONGODB_DB_PORT"));
String username = System.getenv("OPENSHIFT_MONGODB_DB_USERNAME");
String password = System.getenv("OPENSHIFT_MONGODB_DB_PASSWORD");
Mongo mongo = new Mongo(openshiftMongoDbHost, openshiftMongoDbPort);
UserCredentials userCredentials = new UserCredentials(username, password);
String databaseName = System.getenv("OPENSHIFT_APP_NAME");
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, databaseName, userCredentials);
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory);
return mongoTemplate;
}
}
View Code   proxy存储类内部使用MongoTemplate去执行操作,我们定义了一个MongoTemplate bean使用OpenShift MongoDB账户信息。
  以上代码在程序里用@EnableWebMvc 注释激活了Spring MVC支持。

第五步:编写类GetBookmarksWebApplicationInitializer
  3.0版本的Servlet, web.xml是可选的,一般,我们在web.xml里配置Spring WebMVC dispatcher servlet, 这次我们用WebApplicationInitializer编码方式配置,从Spring 3.1开始,提供了一个叫SpringServletContainerInitializer的 ServletContainerInitializer 接口实现。SpringServletContainerInitializer 类委托你提供的org.springframework.web.WebApplicationInitializer 的实现。你只需执行一个方法:WebApplicationInitializer#onStartup(ServletContext). 你需要初始化ServletContext .





import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class GetBookmarksWebApplicationInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.register(ApplicationConfig.class, WebMvcConfig.class);

Dynamic dynamc = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(webApplicationContext));
dynamc.addMapping("/api/v1/*");
dynamc.setLoadOnStartup(1);
}
}
View Code
第六步:创建Story域类
  这个程序,我们只有一个域类Story.





@Document(collection = "stories")
public class Story {
@Id
private String id;
private String title;
private String text;
private String url;
private String fullname;
private final Date submittedOn = new Date();
private String image;
public Story() {
}
// Getter and Setter removed for brevity
View Code   以上代码的重点:


[*]@Docmument注释定义了一个域对象会存入MongoDB, stories指定了集合名,会在MongoDB中创建。
[*]@Id注释 标明这是Id栏,会自动由MongoDB生成。

第七步:创建StoryRepository
  以上提到,Spring MongoDB对你在哪里实现接口有存储概念,Spring会生成一个proxy类。我们来创建如下StoryRepository.





import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.getbookmarks.domain.Story;
@Repository
public interface StoryRepository extends CrudRepository {
public List findAll();
}
View Code   以上代码的重点:


[*]StoryRepository接口继承用于定义CRUD方法和查找方法的CrudRepository接口,所以,Spring生成的proxy有所有这些方法。
[*]@Repository注释限定@Component注释,标明这个类是存储或DAO类。用@Repository注释的类适合Spring DataAccessException      当用户连接 PersistenceExceptionTranslationPostProcessor时的转换。

第八步:编写StoryResource
  接下来,编写在Story上执行创建和阅读操作的REST JSON Web服务。用以下方法创建Spring MVC控制器。





@Controller
@RequestMapping("/stories")
public class StoryResource {
private StoryRepository storyRepository;
@Autowired
public StoryResource(StoryRepository storyRepository) {
this.storyRepository = storyRepository;
}
@RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity submitStory(@RequestBody Story story) {
Story storyWithExtractedInformation = decorateWithInformation(story);
storyRepository.save(storyWithExtractedInformation);
ResponseEntity responseEntity = new ResponseEntity(HttpStatus.CREATED);
return responseEntity;
}
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List allStories() {
return storyRepository.findAll();
}
@RequestMapping(value = "/{storyId}", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Story showStory(@PathVariable("storyId") String storyId) {
Story story = storyRepository.findOne(storyId);
if (story == null) {
throw new StoryNotFoundException(storyId);
}
return story;
}
private Story decorateWithInformation(Story story) {
String url = story.getUrl();
RestTemplate restTemplate = new RestTemplate();
ResponseEntity forEntity = restTemplate.getForEntity(
"http://gooseextractor-t20.rhcloud.com/api/v1/extract?url=" + url, Story.class);
if (forEntity.hasBody()) {
return new Story(story, forEntity.getBody());
}
return story;
}
}
View Code
第九步:安装AngularJS和Twitter Bootstrap
  从对应的官网下载最新的AngularJS和Bootstrap, 或者你也可以从这个项目的github仓库复制资源。

第十步:创建Index.html

现在来完成程序试图。












body {
padding-top: 60px;
}

GetBookmarks : Submit Story










GetBookmarks













View Code   以上代码:


[*]导入了所有需要的库,程序代码在app.js.
[*]在Angular, 用ng-app指令定义项目范围。我们把ng-app用在html元素,不过也可以用其他元素。用html意味着AngularJS在整个index.html都可用,可以给ng-app指令命名,这个名字是模块名,我用getbookmarks作为程序模块名。
[*]最后一个index.htnl里有趣的是ng-view指令的用法。ngView加载当前index.html路径中对应的模板,所以,每次你切换路径只有ng-view这部分更改了。

第十一步:编写AngularJS代码
  App.js 放置了所有JavaScript, 程序所有路径都定义在里面,以下代码,我们定义了三个路径,每个都有一个对应的Angular控制器。





angular.module("getbookmarks.services", ["ngResource"]).
factory('Story', function ($resource) {
var Story = $resource('/api/v1/stories/:storyId', {storyId: '@id'});
Story.prototype.isNew = function(){
return (typeof(this.id) === 'undefined');
}
return Story;
});
angular.module("getbookmarks", ["getbookmarks.services"]).
config(function ($routeProvider) {
$routeProvider
.when('/', {templateUrl: 'views/stories/list.html', controller: StoryListController})
.when('/stories/new', {templateUrl: 'views/stories/create.html', controller: StoryCreateController})
.when('/stories/:storyId', {templateUrl: 'views/stories/detail.html', controller: StoryDetailController});
});
function StoryListController($scope, Story) {
$scope.stories = Story.query();
}

function StoryCreateController($scope, $routeParams, $location, Story) {
$scope.story = new Story();
$scope.save = function () {
$scope.story.$save(function (story, headers) {
toastr.success("Submitted New Story");
$location.path('/');
});
};
}
function StoryDetailController($scope, $routeParams, $location, Story) {
var storyId = $routeParams.storyId;
$scope.story = Story.get({storyId: storyId});
}
View Code
第十二步:部署到云
  最后,提交代码,推送到程序gear.





$ git add .
$ git commit -am "application code"
$ git push
View Code   这就是今天的内容,继续给反馈吧。
原文:https://www.openshift.com/blogs/day-22-developing-single-page-applications-with-spring-mongodb-and-angularjs
页: [1]
查看完整版本: [译] 第二十二天: 用Spring, MongoDB和AngularJS开发单页应用