今天的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上有在线程序,程序有以下功能。
今天的demo放在 github: day22-spring-angularjs-demo-app.
用Tomcat 7和MongoDB cartridge新建程序开始。
$ rhc create-app getbookmarks tomcat-7 mongodb-2
这会创建一个叫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"
注意,那也会删除web.xml.
接下来,用以下代码更新程序的pom.xml.
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>getbookmarks</groupId> <artifactId>getbookmarks</artifactId> <packaging>war</packaging> <version>1.0</version> <name>getbookmarks</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.3.2.RELEASE</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <profiles> <profile> <id>openshift</id> <build> <finalName>getbookmarks</finalName> <plugins> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> <outputDirectory>webapps</outputDirectory> <warName>ROOT</warName> </configuration> </plugin> </plugins> </build> </profile> </profiles> </project>
以上pom.xml:
更新好后,确保更新maven项目 右击> Maven > Update Project.
新建包 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{ }
接下来写另一个配置类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; } }
proxy存储类内部使用MongoTemplate去执行操作,我们定义了一个MongoTemplate bean使用OpenShift MongoDB账户信息。
以上代码在程序里用@EnableWebMvc 注释激活了Spring MVC支持。
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); } }
这个程序,我们只有一个域类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
以上代码的重点:
以上提到,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<Story, String> { public List<Story> findAll(); }
以上代码的重点:
接下来,编写在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<Void> submitStory(@RequestBody Story story) { Story storyWithExtractedInformation = decorateWithInformation(story); storyRepository.save(storyWithExtractedInformation); ResponseEntity<Void> responseEntity = new ResponseEntity<>(HttpStatus.CREATED); return responseEntity; } @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public List<Story> 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<Story> 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; } }
从对应的官网下载最新的AngularJS和Bootstrap, 或者你也可以从这个项目的github仓库复制资源。
现在来完成程序试图。
<!DOCTYPE html> <html ng-app="getbookmarks"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <link rel="stylesheet" href="css/bootstrap.css"/> <link rel="stylesheet" href="css/toastr.css"/> <style> body { padding-top: 60px; } </style> <title>GetBookmarks : Submit Story</title> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="brand" href="#">GetBookmarks</a> </div> </div> </div> <div class="container" ng-view> </div> <script src="js/jquery-1.9.1.js"></script> <script src="js/bootstrap.js"></script> <script src="js/angular.js"></script> <script src="js/angular-resource.js"></script> <script src="js/toastr.js"></script> <script src="js/app.js"></script> </body> </html>
以上代码:
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}); }
最后,提交代码,推送到程序gear.
$ git add . $ git commit -am "application code" $ git push
这就是今天的内容,继续给反馈吧。