[譯] 第二十二天: 用Spring, MongoDB和AngularJS開發單頁應用

前言

今天的30天挑戰,我決定用Spring框架, MongoDBAngularJS開發一個單頁網頁應用。我對Spring和MongoDB很熟悉可是沒有AngualrJS和Spring框架一塊兒用過。因此本文就來開發一個網摘程序就像幾天前用EmberJS寫的同樣。在這個系列的次日咱們已經討論過AngularJS基礎知識,詳情參考博客。本文咱們來討論最新版本的Spring框架如3.2.5 RELEASE, 不採用XML(甚至沒有web.xml). 咱們用Spring註釋支持來配置全部東西,Spring MVC(同Spring框架一塊兒)用來建立RESTful後端。AngularJS用作客戶端MVC框架來開發前端。 css

程序用例

本文咱們開發個網摘程序容許用戶發佈和分享連接。OpenShift上有在線程序,程序有如下功能。html

前提準備

  1. Java基礎知識,安裝最新的Java Development      Kit(JDK), 能夠安裝OpenJDK 7或者Oracle JDK 7, OpenShift支持OpenJDK 6 和7.
  2. Spring基礎知識。
  3. OpenShift上註冊。OpenShift徹底免費,紅帽給每一個用戶免費提供了3個Gears來運行程序。目前,這個資源分配合計有每人1.5GB內存,3GB磁盤空間。
  4. 在本機安裝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.
  5. 用rhc setup 命令安裝OpenShift. 執行命令能夠幫你建立空間,上傳ssh 密鑰到OpenShift服務器。 

Github倉庫

今天的demo放在  github: day22-spring-angularjs-demo-app前端

第一步:建立Tomcat 7程序

用Tomcat 7和MongoDB cartridge新建程序開始。java

$ rhc create-app getbookmarks tomcat-7 mongodb-2
View Code

這會建立一個叫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"
View Code

注意,那也會刪除web.xml. angularjs

第三步:更新po.xml

接下來,用如下代碼更新程序的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>
View Code

以上pom.xml:web

  1. 添加Maven依賴給Spring-webmvc, spring-mongodb,      jackson, 和最新 servlet api.  
  2. 更新項目JDK 6到JDK 7.
  3. 更新項目用最新Maven war插件,添加一個配置避免沒有web.xml時build出錯。 

更新好後,確保更新maven項目 右擊> Maven > Update Project. spring

第四步:編寫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

以上代碼的重點:

  1. @Docmument註釋定義了一個域對象會存入MongoDB, stories指定了集合名,會在MongoDB中建立。
  2. @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<Story, String> { 

    public List<Story> findAll();

}
View Code

以上代碼的重點:

  1. StoryRepository接口繼承用於定義CRUD方法和查找方法的CrudRepository接口,因此,Spring生成的proxy有全部這些方法。
  2. @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<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;

    }

}
View Code

第九步:安裝AngularJS和Twitter Bootstrap

從對應的官網下載最新的AngularJSBootstrap, 或者你也能夠從這個項目的github倉庫複製資源。 

第十步:建立Index.html

如今來完成程序試圖。 

<!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>
View Code

以上代碼:

  1. 導入了全部須要的庫,程序代碼在app.js.
  2. 在Angular, 用ng-app指令定義項目範圍。咱們把ng-app用在html元素,不過也能夠用其餘元素。用html意味着AngularJS在整個index.html均可用,能夠給ng-app指令命名,這個名字是模塊名,我用getbookmarks做爲程序模塊名。
  3. 最後一個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

相關文章
相關標籤/搜索