今天的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框架來開發前端。 css
本文咱們開發個網摘程序容許用戶發佈和分享連接。OpenShift上有在線程序,程序有如下功能。html
今天的demo放在 github: day22-spring-angularjs-demo-app. 前端
用Tomcat 7和MongoDB cartridge新建程序開始。java
$ rhc create-app getbookmarks tomcat-7 mongodb-2
這會建立一個叫gear的程序容器,安裝所需的SELinux策略和cgroup配置,OpenShift也會爲你安裝一個私有git倉庫,克隆到本地,而後它會把DNS傳播到網絡。可訪問 http://getbookmarks-{domain-name}.rhcloud.com/ 查看程序。替換你本身惟一的OpenShift域名(有時也叫命名空間)。 jquery
接下來刪除OpenShift建立的模板代碼。git
$ 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. angularjs
接下來,用如下代碼更新程序的pom.xml.github
<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:web
更新好後,確保更新maven項目 右擊> Maven > Update Project. spring
新建包 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
這就是今天的內容,繼續給反饋吧。